I have one array of bytes. I want to access each of the bytes and want its equivalent binary value(of 8 bits) so as to carry out next operations on it. I've heard of BitSet but is there any other way of dealing with this?
Thank you.
I have one array of bytes. I want to access each of the bytes and want its equivalent binary value(of 8 bits) so as to carry out next operations on it. I've heard of BitSet but is there any other way of dealing with this?
Thank you.
You might find something along the lines of what you're looking in the Guava Primitives package.
Alternatively, you might want to write something like
That's not tested, but the idea is there. There are also easy modifications to the loops/assignment to return an array of something else (say,
int
orlong
).Here is a sample, I hope it is useful for you!
BitSet.valueOf(byte[] bytes)
You may have to take a look at the source code how it's implemented if you are not using java 7
Java has
bitwise operators
. See a tutorial example.A
byte
value IS integral, you can check bit state using masking operations. The least significant bit corresponds to the mask1
or0x1
, the next bit correspond to0x2
, etc.If you just need the String representation of it in binary you can simply use
Integer.toString()
with the optional second parameter set to 2 for binary.To perform general bit twiddling on any integral type, you have to use logical and bitshift operators.