简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM