Java – please explain why 24,16,8 is used to convert ints to bytes?

The following code is to convert int to bytes array

private static byte[] intToBytes(int i)
  // split integer i into 4 byte array
  {
    // map the parts of the integer to a byte array
    byte[] integerBs = new byte[4];
    integerBs[0] = (byte) ((i >>> 24) & 0xFF);
    integerBs[1] = (byte) ((i >>> 16) & 0xFF);
    integerBs[2] = (byte) ((i >>> 8) & 0xFF);
    integerBs[3] = (byte) (i & 0xFF);

    // for (int j=0; j < integerBs.length; j++)
    //  System.out.println(" integerBs[ " + j + "]: " + integerBs[j]);

    return integerBs;
  }  // end of intToBytes()

Solution

Well, pretend you have a 32-bit binary number:

00001111 00000111 00000011 00000001

A byte is equivalent to 8 bits, so the number above consists of 4 bytes

To separate these bytes, we need to perform a series of shift and mask operations

For example, to get the first byte (00001111), we do the following:

00001111 00000111 00000011 00000001 (original)
00000000 00000000 00000000 00001111 (shifted 24 spaces to the right)

Now we don't want these three byte zeros to be in front, so we use an 8-bit mask (0xff) and perform an and operation between our 32-bit result number and the mask

For example:

00000000 00000000 00000000 00001111
&&                         11111111
-----------------------------------
                           00001111 (the first byte)

Now you can imagine how to get the second byte (only 16 bits to the right) The whole goal is to get the 8 bits you want in the first 8 positions and use the mask to get rid of the garbage in front

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>