Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // put an int into a byte array
- int n= 0x01020304; // easyto test if set out in hex
- byte[] bytes = new byte[4];
- bytes[3]=(byte) n; // lowest 8 bits into byte[3]
- n>>=8; // this is n = n >> 8. The >> is a bit shift to the right 8 places
- // so it loses the lower 8 bits, and shifts the rest along
- bytes[2]=(byte) n; // this now gets what was the second lowest 8 bits
- n>>=8;
- bytes[1]=(byte) n; // this would be better as a loop
- n>>=8;
- bytes[0]=(byte) n;
- for (int i=0; i<4; i++)
- System.out.println(bytes[i]); // 1 2 3 4
Advertisement
Add Comment
Please, Sign In to add comment