0

I am working with some code that takes in a binary file as input. However, I am having trouble understanding the for loop in the code, as I don't understand what the bitwise operators do to IFD_Address, such as the |=, <<, and & 0xff. I think IFD_Address refers to a pointer in the binary file, but I am not sure. What is this piece of code trying to achieve?

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++;
}
SDJ
  • 4,083
  • 1
  • 17
  • 35
dcs
  • 31
  • 4

1 Answers1

0

This behavior is best understood in terms of moving bits around, not numbers. Bytes comprise eight bits, integers, 32 bits. The loop basically takes each byte in the array and places the corresponding bits in the integer IFD_Address in 8-bit chunks, from right (least significant) to left (most significant), like this:

enter image description here

About the bitwise operations:

  • & 0xff is required to capture the 8 bits into an integer;
  • << shifts the bits to the left to select the appropriate place in IFD_Address;
  • |= sets the bits in IFD_Address.

See this tutorial for details.

SDJ
  • 4,083
  • 1
  • 17
  • 35