For a project, I have to convert a binary string into (an array of) bytes and write it out to a file in binary.
Say that I have a sentence converted into a code string using a huffman encoding. For example, if the sentence was: “hello” h = 00 e = 01, l = 10, o = 11
Then the string representation would be 0001101011.
How would I convert that into a byte? <– If that question doesn’t make sense it’s because I know little about bits/byte bitwise shifting and all that has to do with manipulating 1’s and 0’s.
If you really want (or have to) creating a string representation of bits, you could split the string in substrings of length 8 (beware of the last one which is not necessarily of length 8).
Integer
has a method to parse string representations, a sequence of ‘0’ and ‘1’s can be parsed by calling with radix = 2.
Parses the string argument as a signed integer in the radix specified by the second argument.
—
EDIT:
According to the comments Byte.parseByte is the way to go.