Hannah
Hannah

Reputation: 25

How to convert unsigned char to binary representation

I'm trying to convert unsigned chars to their hex ASCII values but in binary form.

For example:

unsigned char C to 0100 0011 (43)

I can get from hex to binary the issue is getting from char to its hex value.

for (n = 0; n < 8; n++){
    binary[n] = (letter >> n) & 1;}

I keep getting the wrong values because the letter is going in as its own ASCII value rather than the binary version of the hex ASCII value

Upvotes: 3

Views: 8482

Answers (1)

Elias
Elias

Reputation: 923

I think you are picking the bits one by one just fine, you just get them in reverse order compared to what you wanted.

This works:

#include <stdio.h>
int main() {
  unsigned char letter = 'C';
  int binary[8];
  for(int n = 0; n < 8; n++)
    binary[7-n] = (letter >> n) & 1;
  /* print result */
  for(int n = 0; n < 8; n++)
    printf("%d", binary[n]);
  printf("\n");
  return 0;
}

Running that gives the 01000011 that you wanted.

Upvotes: 1

Related Questions