fork download
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #include <ctype.h>
  5.  
  6. // Simple Base64 decoding table
  7. static const unsigned char b64_table[256] = {
  8. ['A']=0, ['B']=1, ['C']=2, ['D']=3, ['E']=4, ['F']=5, ['G']=6, ['H']=7,
  9. ['I']=8, ['J']=9, ['K']=10, ['L']=11, ['M']=12, ['N']=13, ['O']=14, ['P']=15,
  10. ['Q']=16, ['R']=17, ['S']=18, ['T']=19, ['U']=20, ['V']=21, ['W']=22, ['X']=23,
  11. ['Y']=24, ['Z']=25,
  12. ['a']=26, ['b']=27, ['c']=28, ['d']=29, ['e']=30, ['f']=31, ['g']=32, ['h']=33,
  13. ['i']=34, ['j']=35, ['k']=36, ['l']=37, ['m']=38, ['n']=39, ['o']=40, ['p']=41,
  14. ['q']=42, ['r']=43, ['s']=44, ['t']=45, ['u']=46, ['v']=47, ['w']=48, ['x']=49,
  15. ['y']=50, ['z']=51,
  16. ['0']=52, ['1']=53, ['2']=54, ['3']=55, ['4']=56, ['5']=57, ['6']=58, ['7']=59,
  17. ['8']=60, ['9']=61, ['+']=62, ['/']=63
  18. };
  19.  
  20. // Decodes Base64 string into output buffer, returns output length
  21. int base64_decode(const char *in, unsigned char *out) {
  22. int len = strlen(in);
  23. int i, j = 0;
  24. unsigned int val = 0;
  25. int valb = -8;
  26. for (i = 0; i < len; i++) {
  27. unsigned char c = in[i];
  28. if (isspace(c) || c == '=') continue;
  29. if (c > 127 || b64_table[c] == 0 && c != 'A') continue; // skip invalid
  30. val = (val << 6) + b64_table[c];
  31. valb += 6;
  32. if (valb >= 0) {
  33. out[j++] = (val >> valb) & 0xFF;
  34. valb -= 8;
  35. }
  36. }
  37. return j;
  38. }
  39.  
  40. int main() {
  41. // Base64 string containing "US4Dq"
  42. const char *b64 = "US4Dq9Rdm05Rx/Z79RzHj6RqGHdO+INI/sVJfspO9jJUJmHKPlQH0mEOlSvsU";
  43. unsigned char decoded[128];
  44. int out_len, i;
  45.  
  46. out_len = base64_decode(b64, decoded);
  47.  
  48. printf("Decoded %d bytes:\n", out_len);
  49. for (i = 0; i < out_len; ++i) {
  50. printf("Byte %3d: 0x%02X", i, decoded[i]);
  51. if (decoded[i] == 0x00 || decoded[i] == 0x04 || decoded[i] == 0x1A) {
  52. printf(" <-- problematic byte");
  53. }
  54. printf("\n");
  55. }
  56. return 0;
  57. }
  58.  
Success #stdin #stdout 0s 5316KB
stdin
Standard input is empty
stdout
Decoded 45 bytes:
Byte   0: 0x51
Byte   1: 0x2E
Byte   2: 0x03
Byte   3: 0xAB
Byte   4: 0xD4
Byte   5: 0x5D
Byte   6: 0x9B
Byte   7: 0x4E
Byte   8: 0x51
Byte   9: 0xC7
Byte  10: 0xF6
Byte  11: 0x7B
Byte  12: 0xF5
Byte  13: 0x1C
Byte  14: 0xC7
Byte  15: 0x8F
Byte  16: 0xA4
Byte  17: 0x6A
Byte  18: 0x18
Byte  19: 0x77
Byte  20: 0x4E
Byte  21: 0xF8
Byte  22: 0x83
Byte  23: 0x48
Byte  24: 0xFE
Byte  25: 0xC5
Byte  26: 0x49
Byte  27: 0x7E
Byte  28: 0xCA
Byte  29: 0x4E
Byte  30: 0xF6
Byte  31: 0x32
Byte  32: 0x54
Byte  33: 0x26
Byte  34: 0x61
Byte  35: 0xCA
Byte  36: 0x3E
Byte  37: 0x54
Byte  38: 0x07
Byte  39: 0xD2
Byte  40: 0x61
Byte  41: 0x0E
Byte  42: 0x95
Byte  43: 0x2B
Byte  44: 0xEC