Write a bit in a byte/char

Could anyone help me understand how to insert or write a bit in a byte?

I have a homework where I have to implement Huffman algorithm. I found out the code for each character from the input file and I memorized it in a char matrix code[100][100], where on each line is a code for a character. Now I have to write the output file which contains bits with the code for each character.

Thanks!
Why not try a bitset?
http://www.cplusplus.com/reference/stl/bitset/

Though, if you want/have to do it with chars, then I think maybe the left bitshift operator might be of some interest.
1 << value;
http://www.cs.umd.edu/class/spring2003/cmsc311/Notes/BitOp/bitshift.html

Good luck!

-Albatross
Last edited on
Thanks for your responds.

First of all, I forgot to say that I have to write my homework in C, that's way I have to use the bitshift operator.

I don't know if I understood correct...

For example, if I have:
char byte; //byte may be 11001100
int bit1=1, bit2=0;

If I write:

bit1<<byte; //byte would be: 11100110
bit2<<bye; //byte would be: 01110011

That's correct?
Something like this I would like to do in my homework...







So, if I understand, you want to output the variables in base 2 and not base 10 (output bits not numbers)? That's simple enough in this case, actually. I'll give you some pointers:
To see if a bit is turned on, use if(variable & (1 << /*index of bit*/))
Remember, just like base 10, the first digit is digit 0 and is on the rightmost side when written; the first digit in the number 1753210 is 2, just as the first digit in the number 102 (210) is 0.
You will want to read this page: http://www.cplusplus.com/doc/boolean/
Topic archived. No new replies allowed.