如何将整数拆分为2字节二进制? [英] How do I split an integer into 2 byte binary?
问题描述
给定
private int width = 400;
private byte [] data = new byte [2];
我想将整数width拆分为两个字节,并将数据[0]加载到高位具有低字节的字节和数据[1]。
I want to split the integer "width" into two bytes and load data[0] with the high byte and data[1] with the low byte.
这是二进制值400 = 1 1001 0000
所以data [0]应该包含0000 0001
和data [1]应包含1001 0000
That is binary value of 400 = 1 1001 0000 so data[0] should contain 0000 0001 and data[1] should contain 1001 0000
推荐答案
使用简单的按位运算:
data[0] = (byte) (width & 0xFF);
data[1] = (byte) ((width >> 8) & 0xFF);
工作原理:
-
& 0xFF
屏蔽除最低8位之外的所有字符。 -
>> 8
通过将所有位向右移动8位来丢弃最低8位。 - 转换为字节是必要的,因为这些按位操作适用于
int
并返回int
,这是一个比byte
更大的数据类型。这种情况是安全的,因为所有非零位都适合字节
。有关详细信息,请参阅 转化和促销 。
& 0xFF
masks all but the lowest eight bits.>> 8
discards the lowest 8 bits by moving all bits 8 places to the right.- The cast to byte is necessary because these bitwise operations work on an
int
and return anint
, which is a bigger data type thanbyte
. The case is safe, since all non-zero bits will fit in thebyte
. For more information, see Conversions and Promotions.
编辑: Taylor L 正确评论虽然>>
在这种情况下有效但如果你概括了这个,它可能会产生不正确的结果代码到四个字节(因为在Java中, int
是32位)。在这种情况下,最好使用>>>
而不是>>
。有关详细信息,请参阅关于 Bitwise和Bit的Java教程转移运算符 。
Taylor L correctly remarks that though >>
works in this case, it may yield incorrect results if you generalize this code to four bytes (since in Java an int
is 32 bits). In that case, it's better to use >>>
instead of >>
. For more information, see the Java tutorial on Bitwise and Bit Shift Operators.
这篇关于如何将整数拆分为2字节二进制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!