How do I base64 encode (decode) in C?

后端 未结 17 1695
孤城傲影
孤城傲影 2020-11-22 06:27

I have binary data in an unsigned char variable. I need to convert them to PEM base64 in c. I looked in openssl library but i could not find any function. Does any body have

17条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 06:48

    GNU coreutils has it in lib/base64. It's a little bloated but deals with stuff like EBCDIC. You can also play around on your own, e.g.,

    char base64_digit (n) unsigned n; {
      if (n < 10) return n - '0';
      else if (n < 10 + 26) return n - 'a';
      else if (n < 10 + 26 + 26) return n - 'A';
      else assert(0);
      return 0;
    }
    
    unsigned char base64_decode_digit(char c) {
      switch (c) {
        case '=' : return 62;
        case '.' : return 63;
        default  :
          if (isdigit(c)) return c - '0';
          else if (islower(c)) return c - 'a' + 10;
          else if (isupper(c)) return c - 'A' + 10 + 26;
          else assert(0);
      }
      return 0xff;
    }
    
    unsigned base64_decode(char *s) {
      char *p;
      unsigned n = 0;
    
      for (p = s; *p; p++)
        n = 64 * n + base64_decode_digit(*p);
    
      return n;
    }
    

    Know ye all persons by these presents that you should not confuse "playing around on your own" with "implementing a standard." Yeesh.

提交回复
热议问题