无符号 16 和 64 位整数
如何在 Java 中生成 16 位无符号整数和 64 位无符号整数?这个问题与实施标准有关。我无法更改规格。
规范的其他可能相关的部分。这个问题与:
- 最高有效位必须为0。
- 必须以网络字节顺序表示。
应用程序上下文:数字(任一形式)表示正在发送的数据的长度。长度可大可小。我首先发现要发送的消息的长度为 long。
所以我从: long length = getLength();
然后我需要将 long 变量“length”转换为上述两者之一,具体取决于它有多大。最后,我很确定在发送长度时需要执行 .getBytes()
。接收者将按照上述方式进行解释。
How do you produce a 16 bit unsigned integer and a 64-bit unsigned integer in Java? This question is related to implementing a standard. I am not in a position to change the spec.
Other perhaps relevant bits of the spec. this question is related to:
- most significant bit MUST be 0.
- must be expressed in network byte order.
Application context: The number (in either form) represents the length of data being sent. The length can be big or small. I've first found the length of the message to be sent as a long.
So I'm starting with: long length = getLength();
I then need to convert the long variable "length" to either of the two above, depending on how big it is. In the end, I'm pretty sure I'll need to do a .getBytes()
when I send the length. The recipient will interpret as described above.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果最高有效位必须为零,则无论有符号还是无符号,该数字都是相同的(假设采用二进制补码表示)。例如,MSB 为零的 16 位整数表示从
0
到32767
的数字(含)。假设您正在写入
OutputStream
并且您对“网络顺序”的定义是最高有效字节在前,那么您需要执行如下操作:请
注意,这些适用于有符号和无符号整数。 (或者更准确地说,对于 Java 上下文,如果参数表示有符号或无符号整数,它们就起作用。)
If the most significant bit must be zero, then the number is the same whether it is signed or unsigned (assuming a two's complement representation). So for instance, 16 bit integers with the MSB zero represent the numbers from
0
to32767
inclusive.Assuming that you are writing to an
OutputStream
and that your definition of "network order" is most significant byte first, then you need to do something like this:and
Note that these works for signed and unsigned integers. (Or to be more precise for the Java context, they work if the argument represents a signed or unsigned integer.)
Java 没有无符号数据类型(请参见此处:http://darksleep.com/player/JavaAndUnsignedTypes.html)
int 有 32 位,long 有 64 位,short 有 16 位,
将它们都存储为 long 是不是很糟糕?
Java has no unsigned datatypes (see here: http://darksleep.com/player/JavaAndUnsignedTypes.html)
int has 32bit, long has 64bit, short has 16bit
is it so bad to store it all just as long?