Java中如何将一个int转换为三个字节?
我正在尝试将 int
转换为代表该 int
(大端)的三个 字节
。
我确信它与按位和移位有关。 但我不知道该怎么做。
例如:
int myInt;
// some code
byte b1, b2 , b3; // b1 is most significant, then b2 then b3.
*注意,我知道 int 是 4 个字节,这三个字节有可能上溢/下溢。
I am trying to convert an int
into three bytes
representing that int
(big endian).
I'm sure it has something to do with bit-wise and and bit shifting. But I have no idea how to go about doing it.
For example:
int myInt;
// some code
byte b1, b2 , b3; // b1 is most significant, then b2 then b3.
*Note, I am aware that an int is 4 bytes and the three bytes have a chance of over/underflowing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
要获取最低有效字节:
第二个最低有效字节:
和第三个最低有效字节:
说明:
按位与 0xFF(二进制为 11111111)的值将返回最低有效 8 位(位 0)至 7) 在该数字中。 将数字右移 8 次会将位 8 到 15 放入位位置 0 到 7,因此与 0xFF 进行 AND 运算将返回第二个字节。 类似地,将数字右移 16 次会将位 16 到 23 放入位位置 0 到 7,因此与 0xFF 进行 AND 运算将返回第 3 个字节。
To get the least significant byte:
The 2nd least significant byte:
And the 3rd least significant byte:
Explanation:
Bitwise ANDing a value with 0xFF (11111111 in binary) will return the least significant 8 bits (bits 0 to 7) in that number. Shifting the number to the right 8 times puts bits 8 to 15 into bit positions 0 to 7 so ANDing with 0xFF will return the second byte. Similarly, shifting the number to the right 16 times puts bits 16 to 23 into bit positions 0 to 7 so ANDing with 0xFF returns the 3rd byte.
我不确定这个在java中是如何实现的,我不是java开发者
I am unsure how this holfds in java though, i aam not a java dev
int 不能容纳 3 个字节。 但是,假设您知道这些特定的内容:
An int doesn't fit into 3 bytes. However, assuming that you know these particular ones do:
在 Java 中
输出 0 0 1
In Java
outputs 0 0 1
如果是正整数值,Jeremy 的答案是正确的。 如果转换对于负值应该是正确的,由于二进制补码格式,它会稍微复杂一些( https://en.wikipedia.org/wiki/Two%27s_complement)。 诀窍是消除感兴趣的位(较低有效位)和“符号”位之间的间隙。 一种简单的方法是数字相乘。
这将以正确的负值补码格式结束。
PS:您可以这样检查和比较二进制表示:
The answer of Jeremy is correct in case of positive integer value. If the conversion should be correct for negative values, it is little more complicated due to two's-complement format (https://en.wikipedia.org/wiki/Two%27s_complement). The trick is to remove the gap between the interesting bits (the less significant bits) and the 'sign' bit. One easy method is multiplication of the number.
This will end up with correct two's-complement format for negative values.
PS: You can check and compare binary representation this way: