0

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?

3
  • 1
    What is the actual starting info you have? Because the first line is obviously not correct, do you have a string "01011110" or do you have a string "^"? Commented Nov 6, 2021 at 12:19
  • It's supposed to be String binaryString = "01011110"; .Sorry about that. Commented Nov 6, 2021 at 12:23
  • Byte.parseByte("01011110", 2) Commented Nov 6, 2021 at 12:25

3 Answers 3

2

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

The second argument to parseByte() lets you specify the Number system in which the String should be parsed. By default, a radix of 10 is used because us humans usually use the decimal system. The 2 says that the number should be treated as a binary value (which is base 2).

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you! What does 2 mean on the second line?
It lets you specify the numerical system in which the String should be parsed. By default, a radix of 10 is used because us humans usually use the decimal system. The 2 says that the number should be treated as a binary value (which is base 2).
Ahh, okay! When my program comes to the next binaryString, I get this exception NumberFormatException: Value out of range. Value:"10000011" Radix:2. What is wrong?
Byte can only represent numbers from -128 to 127, and 10000011 is 131.
You can use byte i = (byte)(Integer.parseInt("10000011", 2) & 0xff)
1

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

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

example:

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

Comments

0

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.