11

I'm flummoxed by how to convert from a binary value to a char in c.

For example, let's say I have 01010110 and want to print the corresponding letter 'V' from that. How do I do this?

Thanks for any help!

Jordan
  • 2,070
  • 6
  • 24
  • 41

3 Answers3

18
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
    char *data = "01010110";
    char c = strtol(data, 0, 2);
    printf("%s = %c = %d = 0x%.2X\n", data, c, c, c);
    return(0);
}

Output:

01010110 = V = 86 = 0x56

References:

Community
  • 1
  • 1
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
6

You can use strtol() to parse a number on a string. The last argument (in this case 2) is the radix for the conversion.

char c = strtol("01010110", (char **)NULL, 2);

More information about this and other number parsing functions here.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
fbafelipe
  • 4,862
  • 2
  • 25
  • 40
-2

Did something slightly different:

From the binary, I mathematically calculated the int and simply casted the int into a char.

int i;
char c = (char)i;
Jordan
  • 2,070
  • 6
  • 24
  • 41
  • The final conversion is self-evident; the hand-waving 'from the binary, I mathematically calculated the int' contains no useful information. – Jonathan Leffler Aug 04 '16 at 15:25