zarcel
zarcel

Reputation: 1241

How to modify single bit in a byte array element?

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?

Upvotes: 1

Views: 3843

Answers (2)

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.

Upvotes: 1

Louis Wasserman
Louis Wasserman

Reputation: 198023

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);

Upvotes: 5

Related Questions