-6

I want to create a function that converts a binary (int type) to string. for example : if i have this 01001000 01100101 01101100 01101100 01101111 00100000 01010111 01101111 01110010 01101100 01100100

the function should return "Hello World".

Vasilis Stergiou
  • 17
  • 1
  • 1
  • 1

2 Answers2

2

Basicly you must convert the binary code in decimal number (see the table at http://www.asciitable.com/ ). E.g. - 01001000 = 72 (ASCII -> H), 01100101 = 101 (ASCII -> e), etc... Conversion between binary and decimal is very simple: 01001000 = (0 * 10^7) + (1* 10^6) + (0 * 10^5) + (0 * 10^4) + (1 * 10^3) + (0 * 10^2) + (0 * 10^1) + (0 * 10^0) = 0 + 64 + 0 + 0 + 8 + 0 + 0 + 0 = 72 (in ASCII code = H)

Stefano
  • 60
  • 1
  • 1
  • 8
0

I think strtol is the way you should go.

https://www.tutorialspoint.com/c_standard_library/c_function_strtol.htm

Break your letters in peaces o 8 to get individual chars.

Here you got an example: Convert from a binary to char in C

Edit:

#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);
}
Community
  • 1
  • 1
Joe Torres
  • 95
  • 7
  • 1
    In other approach you can convert from bin to int and use char c = (char) int_val; – Joe Torres Apr 03 '17 at 14:51
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/15728456) – MD XF Apr 03 '17 at 15:55
  • Gotit. I will edit the answer. – Joe Torres Apr 03 '17 at 17:48