1

I want to convert a read bit from a binary file to a char so I can add it to a string that would represent a binary format of a file's content. My task is also to read a file byte by byte. I have a following code:

while(f.get(c)){ for(int i=0;i<8;i++){ cout << ((c>>i)&1); //I would like to convert a single bit to a char here } } 

I cannot figure out how to do it since if I simply add ((c>>i)&1) to string I get a binary form for every bit read so 0 becomes 00000000. Can anyone help me? Thank you in beforehand.

2 Answers 2

2

A single bit b (is, or) can be converted to a bool. In your case bool b = (c>>i)&1;

So you may want to code b?'1':'0' using the ternary conditional operator.

You could also code "01"[(unsigned)b] (or just "01"[b]) or (char)('0'+(unsigned)b) but I feel it is less readable to humans (and both only work because (unsigned)b can only be 0 or 1).

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

1 Comment

Is the cast needed? "01"[true] means *("01"+true). Overload resolution is unambiguous as only true needs to be promoted.
2

You need bitset from #include <bitset>

while( f.get(c) ) { bitset<sizeof(c) * CHAR_BIT> currentByte(c); cout << currentByte; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.