I'm having trouble with storing bits as a byte. I've read probably 30 different sources about this already. I'm doing Huffman Compression. Lets say I read in the character "c" and I am supposed to output "1010". How would I go about doing that? I know how to write bytes to an output stream, my problem is generating the bytes in the first place. My question is very similar to a question I found elsewhere on the web that received this response:

"Don't do that. Use the bit manipulation operations to create an integer - you need to store the accumulated bits, and the number of bits you've written to it. When you have 8 bits, write those out as a byte, and shift the stored value right by 8 and reduce the count by 8. That way you can write irregular numbers of bits, and don't even have to convert numbers and strings. "

I understand the need for 'waiting until you have 8 bits' to write the byte. However, what would a method look like that recursively changed the bits 0000 to 1111, one at a time? The problem is - if we have 0000, in order to change the second bit to a 1, don't I have to do

0000 | 0010

So this causes issues if I don't know what bit I'm currently "on", and just want to recursively "add" a series of bits and create a byte out of it. What I want to do looks more like String concatenation, except I want to do it for a byte, and I want to do it a lot more efficiently than can be done w/ Strings.

So, for example, if this was possible, this would be what I'd want to do:

byte current = empty;
for (int i = 0; i < 8, i++)
current += 1;

and have current come out as 11111111

1
Contributor
1
Reply
2
Views
9 Years
Discussion Span
Last Post by BestJewSinceJC

Actually, wait lol. After all this time spent trying to figure this out, I stopped thinking about it and I think it just came to me. If I do

byte current = 00000000;
current = current | 1;
that will make current = 00000001, right?

Then, the next time I wanted to add a bit to the front, I could shift the current bits over 1 and do another OR. No?

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.