BSchlinker BSchlinker - 3 months ago 15
C Question

Bytes to Binary in C

I'm trying to simply convert a byte received from fget into binary.

I know the value of the first byte was 49 based on printing the value. I now need to convert this into its binary value.

unsigned char byte = 49;// Read from file
unsigned char mask = 1; // Bit mask
unsigned char bits[8];

// Extract the bits
for (int i = 0; i < 8; i++) {
// Mask each bit in the byte and store it
bits[i] = byte & (mask << i);
}
// For debug purposes, lets print the received data
for (int i = 0; i < 8; i++) {
printf("Bit: %d\n",bits[i]);
}


This will print:

Bit: 1
Bit: 0
Bit: 0
Bit: 0
Bit: 16
Bit: 32
Bit: 0
Bit: 0
Press any key to continue . . .


Clearly, this is not a binary value. Any help?

Answer

The problem you're having is that your assignment isn't resulting in a true or false value.

bits[i] = byte & (mask << i);

This gets the value of the bit. You need to see if the bit is on or off, like this:

bits[i] = (byte & (mask << i)) != 0;