Converting String type binary number to bit in java

Dc Redwing picture Dc Redwing · Dec 4, 2012 · Viewed 12k times · Source

I have a question about converting String type binary number to bit and write in the txt file.

For example we have String like "0101011" and want to convert to bit type "0101011" then write in to the file on the disk.

I would like to know is there anyway to covert to string to bit..

i was searching on the web they suggest to use bitarray but i am not sure

thanks

Answer

Ted Hopp picture Ted Hopp · Dec 4, 2012

Try this:

int value = Integer.parseInt("0101011", 2); // parse base 2

Then the bit pattern in value will correspond to the binary interpretation of the string "0101011". You can then write value out to a file as a byte (assuming the string is no more than 8 binary digits).

EDIT You could also use Byte.parseByte("0101011", 2);. However, byte values in Java are always signed. If you tried to parse an 8-bit value with the 8th bit set (like "10010110", which is 150 decimal), you would get a NumberFormatException because values above +127 do not fit in a byte. If you don't need to handle bit patterns greater than "01111111", then Byte.parseByte works just as well as Integer.parseInt.

Recall, though, that to write a byte to a file, you use OutputStream.write(int), which takes an int (not byte) value—even though it only writes one byte. Might as well go with an int value to start with.