java - Please explain me why 24,16, 8 were used in converting int to bytes? -


the following code convert int bytes array. know int i right shifted 24, 16, 8 times , anded 0xff can't understand why these numbers used?

private static byte[] inttobytes(int i)   // split integer 4 byte array   {     // map parts of integer 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);      // (int j=0; j < integerbs.length; j++)     //  system.out.println(" integerbs[ " + j + "]: " + integerbs[j]);      return integerbs;   }  // end of inttobytes() 

ok lets pretend have 32 bit binary number:

00001111 00000111 00000011 00000001 

one byte equivalent 8 bits , therefore number above comprised of 4 bytes.

to separate these bytes out need perform series of shift , and mask operations.

for instance first byte (00001111) following:

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

now not want 3 bytes of zeros infront use 8-bit mask (0xff) , perform and operation between our 32 bit resulting number , mask.

for example:

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

now can imagine how second byte (only shift 16 bits right). whole purpose 8 bits want in first 8 positions , use mask rid of garbage infront.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -