Alex Rivera | Logout

Bytes to Binary in C

Asked 2009-11-05T19:36:31.500
10

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?

Edit
Report

1 Answer

4

One way, among many:

#include <stdio.h>
#include <limits.h>

int main(void) {
    int i;
    char bits[CHAR_BIT + 1];
    unsigned char value = 47;

    for (i = CHAR_BIT - 1; i >= 0; i -= 1) {
        bits[i] = '0' + (value & 0x01);
        value >>= 1;
    }

    bits[CHAR_BIT] = 0;

    puts(bits);

    return 0;
}
answered 2009-11-05T19:38:40.927

Your Answer