3

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

Hannah
  • 25
  • 1
  • 3
  • The code should work, you're just reading it from right to left. Also take care, if it is really **unsigned** char, otherwise you might have a problem with arithmetic shift. If you need more help, try providing more context for the code (how you get the letter, what you expect to get, what you're actually getting, how you're printing the result, etc.) – Ordoshsen Sep 22 '19 at 18:57
  • 2
    Try `for(int n = 7; n >= 0; n--)` instead. – Weather Vane Sep 22 '19 at 19:01
  • @WeatherVane That does not produce another result. `letter` is never changed. – the busybee Sep 22 '19 at 20:28
  • @Ordoshsen With the code shown there will be no problem with `signed char` as long as `char`s are at least 8 bits wide. – the busybee Sep 22 '19 at 20:30
  • @JavaNewbie Please show us some of the wrong values. I don't see any real error in the code you provided so far. Perhaps the error is in other parts of your program. It would help a lot if you show us a [example]. – the busybee Sep 22 '19 at 20:32
  • @thebusybee you're right, I guess I jumped the gun when I saw the shift and arithmetic shift came to my mind (it's implementation defined behaviour). It does not matter here anyway. However chars are required to be at least 8 bits (specifically to hold at least 256 values and be one byte in size) and with how the shifts are defined (multiplication or division by a power of two), so the whole thing has to work by default. – Ordoshsen Sep 22 '19 at 21:01

1 Answers1

1

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.

Elias
  • 913
  • 6
  • 22