Created
November 30, 2014 20:23
-
-
Save bigdragon1977/0d361c07555600ffc9dd to your computer and use it in GitHub Desktop.
Using simple bitwise operations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //Using simple bitwise operations: | |
| data[0] = (byte) (width & 0xFF); | |
| data[1] = (byte) ((width >> 8) & 0xFF); | |
| //How it works: | |
| /* | |
| & 0xFF masks all but the lowest eight bits. | |
| >> 8 discards the lowest 8 bits by moving all bits 8 places to the right. | |
| The cast to byte is necessary because these bitwise operations work on an int and return an int, which is a bigger data type than byte. The case is safe, since all non-zero bits will fit in the byte. For more information, see Conversions and Promotions. | |
| Edit: Taylor L correctly remarks that though >> works in this case, it may yield incorrect results if you generalize this code to four bytes (since in Java an int is 32 bits). In that case, it's better to use >>> instead of >>. For more information, see the Java tutorial on Bitwise and Bit Shift Operators. | |
| */ | |
| data[0] = (byte) width; | |
| data[1] = (byte) (width >>> 8); | |
| data[2] = (byte) (width >>> 16); | |
| data[3] = (byte) (width >>> 24); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment