1

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?

2 Answers 2

5

If you want to set it, do

bytes[0] |= (byte) (1 << 5);

...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.

If you want to clear the 5th bit, do

bytes[0] &= (byte) ~(1 << 5);
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.