Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bytes to Binary in C

Tags:

c

binary

byte

bit

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?

like image 395
BSchlinker Avatar asked Nov 05 '09 19:11

BSchlinker


People also ask

How do you convert bytes to binary?

In Java, we can use Integer. toBinaryString(int) to convert a byte to a binary string representative. Review the Integer. toBinaryString(int) method signature, it takes an integer as argument and returns a String.

What is a byte in c?

A byte is typically 8 bits. C character data type requires one byte of storage. A file is a sequence of bytes. A size of the file is the number of bytes within the file. Although all files are a sequence of bytes,m files can be regarded as text files or binary files.

How do you convert bytes to strings?

One method is to create a string variable and then append the byte value to the string variable with the help of + operator. This will directly convert the byte value to a string and add it in the string variable.

How binary works in c?

Binary AND Operator copies a bit to the result if it exists in both operands. Binary OR Operator copies a bit if it exists in either operand. Binary XOR Operator copies the bit if it is set in one operand but not both. Binary One's Complement Operator is unary and has the effect of 'flipping' bits.


2 Answers

Change

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

to

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

or

bits[i] = (byte >> i) & 1;

or

bits[i] = byte & 1;
byte >>= 1;
like image 108
qrdl Avatar answered Sep 18 '22 12:09

qrdl


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;
like image 36
Aaron Avatar answered Sep 18 '22 12:09

Aaron