不明白这些按位运算符是如何对字节和整数进行运算的
Don't understand how these bitwise operators operate on bytes and integers
我正在使用一些将二进制文件作为输入的代码。但是,我无法理解代码中的 for 循环,因为我不明白按位运算符对 IFD_Address
做了什么,例如 |=
、<<
和 & 0xff
。我认为 IFD_Address
指的是二进制文件中的指针,但我不确定。这段代码试图实现什么?
byte[] IFD_Address_tmp = Arrays.copyOfRange(bytes, 4, 8);
int IFD_Address = 0;
int i = 0;
int shiftBy = 0;
for (shiftBy = 0; shiftBy < 32; shiftBy += 8) {
IFD_Address |= ((long) (IFD_Address_tmp[i] & 0xff)) << shiftBy;
i++;
}
最好从移动位而不是数字的角度来理解此行为。字节包括八位,整数,32位。循环基本上获取数组中的每个字节,并将整数 IFD_Address
中的相应位以 8 位块的形式从右(最低有效位)到左侧(最高有效位)放置,如下所示:
关于位运算:
& 0xff
需要 capture the 8 bits into an integer;
<<
将位向左移动到 select IFD_Address
; 中的适当位置
|=
设置 IFD_Address
. 中的位
详情见this tutorial。
我正在使用一些将二进制文件作为输入的代码。但是,我无法理解代码中的 for 循环,因为我不明白按位运算符对 IFD_Address
做了什么,例如 |=
、<<
和 & 0xff
。我认为 IFD_Address
指的是二进制文件中的指针,但我不确定。这段代码试图实现什么?
byte[] IFD_Address_tmp = Arrays.copyOfRange(bytes, 4, 8);
int IFD_Address = 0;
int i = 0;
int shiftBy = 0;
for (shiftBy = 0; shiftBy < 32; shiftBy += 8) {
IFD_Address |= ((long) (IFD_Address_tmp[i] & 0xff)) << shiftBy;
i++;
}
最好从移动位而不是数字的角度来理解此行为。字节包括八位,整数,32位。循环基本上获取数组中的每个字节,并将整数 IFD_Address
中的相应位以 8 位块的形式从右(最低有效位)到左侧(最高有效位)放置,如下所示:
关于位运算:
& 0xff
需要 capture the 8 bits into an integer;<<
将位向左移动到 selectIFD_Address
; 中的适当位置
|=
设置IFD_Address
. 中的位
详情见this tutorial。