问题描述
我想转换一个 INT
成三个字节
重新presenting了 INT
(大端)。
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.
例如:
int myInt;
// some code
byte b1, b2 , b3; // b1 is most significant, then b2 then b3.
*注意,我知道一个int是4字节和三个字节的上/下溢的机会。
*Note, I am aware that an int is 4 bytes and the three bytes have a chance of over/underflowing.
推荐答案
要获得最显著字节:
b3 = myInt & 0xFF;
第二最小显著字节:
The 2nd least significant byte:
b2 = (myInt >> 8) & 0xFF;
和第三至少显著字节:
b1 = (myInt >> 16) & 0xFF;
说明:
按位与运算为0xFF的值(11111111二进制)将在该号码返回至少显著8位(位0到7)。移位数到右边的8倍把位8到15进位位置0到7,以便与运算为0xFF将返回第二个字节。同样地,移数到右边16次把位16到23为位位置0到7所以AND运算为0xFF返回第三个字节。
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.
这篇关于我怎样才能把一个int到Java的三个字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!