Home > OS >  How can I convert a binary string to a byte?
How can I convert a binary string to a byte?

Time:11-06

I'm working on Huffman compression.

String binaryString = "01011110";
outFile.write(byte);

I have a String which I want to convert to a byte so that I can write that byte to the file. Does anyone know how I can do this?

CodePudding user response:

You can turn that String into a numerical value using the overloaded parseByte that lets you specify the radix:

String binaryString = "01011110";
byte b = Byte.parseByte(binaryString, 2); //this parses the string as a binary number
outFile.write(b);

CodePudding user response:

You can use Byte.parseByte() with a radix of 2:

byte b = Byte.parseByte(str, 2);

example:

System.out.println(Byte.parseByte("01100110", 2));

CodePudding user response:

Could write (a String[256] with each manually written 1 and 0 set of 8 bits) it out , its only 256 of them. gives you the ability to check with String.indexOf(binnum[arrayIndex]) and make a corresponding array of new byte[256] and set each in matching order with new Integer(increment).byteValue(), it should reproduce for checking printable over the byte[] array using new Byte(bytarray[incr]).intValue() "\n"

  • Related