简体   繁体   English

将长度为3的字节数组转换为int

[英]Converting byte array of length 3 into an int

I have a byte array of length 3, representing a decimal binary number. 我有一个长度为3的字节数组,表示 十进制 二进制数。 My question: 我的问题:

Why is this correct: 为什么这是正确的:

(a) int x = (array[0] & 0xff) << 16 | (array[1] & 0xff) << 8 | (array[2] & 0xff); (a) int x = (array[0] & 0xff) << 16 | (array[1] & 0xff) << 8 | (array[2] & 0xff); int x = (array[0] & 0xff) << 16 | (array[1] & 0xff) << 8 | (array[2] & 0xff);

but this isn't? 但这不是?

(b) int x = array[0] << 16 | array[1] << 8 | array[2]; (b) int x = array[0] << 16 | array[1] << 8 | array[2]; int x = array[0] << 16 | array[1] << 8 | array[2];

Let's say array[0] is 01010101 . 假设array [0]是01010101 Isn't this what happens? 这不是发生了什么?

array[0] & 0xff = 01010101 & 11111111 = 01010101 = array[0]

Why is option b) wrong? 为什么选项b)错了?

Consider what happens when the most significant bit of array[0] is 1. 考虑当array[0]的最高位为1时会发生什么。

For example: 例如:

array[0] = (byte)0xff;
System.out.println (array[0] << 16);
System.out.println ((array[0] & 0xff) << 16);

output: 输出:

-65536
16711680

array[0] is converted to an int for the sake of the left-shift operator. 为了左移运算符, array[0]被转换为int If it has a negative value as a byte , it will have a negative value as an int , and will have a negative value after the left-shift. 如果它具有作为byte的负值,则它将具有作为int的负值,并且在左移之后将具有负值。

When you perform bit-wise AND with 0xff , you make sure the result will be positive. 当您使用0xff执行按位AND时,确保结果为正。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM