Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a byte into bits?

Tags:

java

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.

like image 736
Supereme Avatar asked Nov 04 '10 09:11

Supereme


People also ask

How do you convert bits to bytes?

To convert from bits to bytes, simply divide the number of bits by 8. For example, 256 bits are equal to 256 / 8 = 32 bytes.

How many bits is a byte?

While a byte can hold a letter or symbol, a bit is the smallest unit of storage, storing just one binary digit. The standard number of bits in a byte is eight, but that number can vary from system to system, depending on the hardware.

Does 8 bits equal 1 byte?

On almost all modern computers, a byte is equal to 8 bits. Large amounts of memory are indicated in terms of kilobytes, megabytes, and gigabytes.


3 Answers

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.

// tests if bit is set in value
boolean isSet(byte value, int bit){
   return (value&(1<<bit))!=0;
} 

// returns a byte with the required bit set
byte set(byte value, int bit){
   return value|(1<<bit);
}
like image 86
MAK Avatar answered Sep 18 '22 17:09

MAK


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

public boolean[] convert(byte...bs) {
 boolean[] result = new boolean[Byte.SIZE*bs.length];
 int offset = 0;
 for (byte b : bs) {
  for (int i=0; i<Byte.SIZE; i++) result[i+offset] = (b >> i & 0x1) != 0x0;
  offset+=Byte.SIZE;
 }
 return result;
}

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 or long).

like image 21
Carl Avatar answered Sep 19 '22 17:09

Carl


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

like image 20
codeplay Avatar answered Sep 18 '22 17:09

codeplay