fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. const char *string2bin_ar[] = {
  6. "0000", // 0
  7. "0001", // 1
  8. "0010", // 2
  9. "0011", // 3
  10. "0100", // 4
  11. "0101", // 5
  12. "0110", // 6
  13. "0111", // 7
  14. "1000", // 8
  15. "1001", // 9
  16. "1010", // A
  17. "1011", // B
  18. "1100", // C
  19. "1101", // D
  20. "1110", // E
  21. "1111", // F
  22. };
  23.  
  24.  
  25. char *
  26. string2binstr(char *hexstring) {
  27. size_t len = strlen(hexstring);
  28. size_t idx = 0;
  29. unsigned char no;
  30. char *out;
  31. if (!len) {
  32. fprintf(stderr, "string2bin: no input data");
  33. return NULL;
  34. }
  35. /* string can't be less then 32 bits (chars in sample)
  36.   * 32 (minimum length) / 4 (hex chunk length) = 8 (number of hex chuncks) */
  37. out = calloc(1, (len < 8 ? 32 : len * 4 ) + 1);
  38. if (!out) {
  39. fprintf(stderr, "string2bin: no enough memory\n");
  40. return NULL;
  41. }
  42. out[len * 4] = '\0';
  43. for (; idx < len; idx++) {
  44. no = (unsigned char)hexstring[idx];
  45. if (no >= '0' && no <= '9')
  46. no -= '0';
  47. else if (no >= 'A' && no <= 'F')
  48. no -= ('A' - 10);
  49. else if (no >= 'a' && no <= 'f')
  50. no -= ('a' - 10);
  51. else no = 0;
  52. memcpy(&out[idx * 4], string2bin_ar[no], 4);
  53. }
  54. /* fill missing bits (bytes) */
  55. if (idx < 8)
  56. memset(&out[idx * 4], '0', 32 - idx * 4);
  57. return out;
  58. }
  59.  
  60. int main(int argc, char *argv[])
  61. {
  62. printf("%s\n", string2binstr("FF"));
  63.  
  64. return 0;
  65. }
Success #stdin #stdout 0s 2424KB
stdin
Standard input is empty
stdout
11111111000000000000000000000000