Java 中的无符号整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4449100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unsigned Int in Java
提问by cdecker
I'm trying to implement an existing network protocol which makes heavy use of Unsigned datatypes, which are not supported by Java. What I currently do is for each datatype, chose the next bigger one so that the unsigned number may fit into the positive region and then use byte shifting to get the desired effect. Since this is pretty error prone and for an unsigned long onward I have to use BigInteger which is a lot heavier than expanded types, I was wondering if there isn't a better way to achieve this?
我正在尝试实现一个现有的网络协议,该协议大量使用 Java 不支持的未签名数据类型。我目前所做的是针对每种数据类型,选择下一个更大的数据类型,以便无符号数适合正数区域,然后使用字节移位来获得所需的效果。由于这很容易出错,并且对于 unsigned long 以后的类型,我必须使用比扩展类型重得多的 BigInteger,我想知道是否有更好的方法来实现这一点?
采纳答案by Peter Lawrey
Depending on what you are doing, you can just treat long as a 64-bit value and int as a 32-bit value. Most operations esp readInt/Long writeInt/Long work just the same by ignoring the signness.
根据您在做什么,您可以将 long 视为 64 位值,将 int 视为 32 位值。大多数操作 esp readInt/Long writeInt/Long 通过忽略符号来工作。
Can you give an example of operation you perform on these numbers and perhaps we can suggest how would do the same thing without having to expand the type.
你能举一个你对这些数字执行的操作的例子,也许我们可以建议如何在不扩展类型的情况下做同样的事情。
For example, ++, --, +, -, *, ==, !=, << all work the same regardless of signess (i.e. give the same answer). for >> you can substitue >>>
例如,++、--、+、-、*、==、!=、<< 无论符号如何都一样(即给出相同的答案)。对于 >> 你可以替换 >>>
It is the /, %, >, >=, <, <= and printing functions which assume signed values, but you should be able to work around these (if you use these).
假定有符号值的是 /、%、>、>=、<、<= 和打印函数,但您应该能够解决这些问题(如果您使用这些)。
e.g.
例如
long unsignedA =
long unsignedB =
boolean greater = unsignedA + Long.MIN_VALUE > unsignedB + Long.MIN_VALUE
EDIT: Why does this work? Partly because java doesn't have overflow/underflow exceptions.
编辑:为什么这有效?部分原因是 java 没有溢出/下溢异常。
e.g.
例如
byte unsignedA = 0;
unsignedA--;
// unsignedA == FF, is this -1 or 255? Java assumes the former but you assume the later
byte unsignedB = unsignedA * unsignedA;
// unsignedB is -1 * -1 = 1 or (byte) (255*255) = (byte) 65525 = 1.