I have array of bytes each holding one byte which is 8 bits. Lets say I want to modify 5th bit of first element of the array without changing anything else. Is there any simple way to do it?
...which OR's the first element in the byte array with the binary representation of 1, shifted to the left 5 places...which is the same thing as setting the 5th bit.
Sign up to request clarification or add additional context in comments.
Comments
1
If you have byte[] a, you can modify the 5th bit of the first element using bit operations like this:
set to 1: a[0] |= 1<<5
set to 0: a[0] &= ~(1<<5)
If you want a nicer API that wraps the bit operations, check out the BitSet class.