How do I encode and decode a base64 string?

前端 未结 10 2525
我在风中等你
我在风中等你 2020-11-22 03:41
  1. How do I return a base64 encoded string given a string?

  2. How do I decode a base64 encoded string into a string?

10条回答
  •  天命终不由人
    2020-11-22 04:23

    For those that simply want to encode/decode individual base64 digits:

    public static int DecodeBase64Digit(char digit, string digit62 = "+-.~", string digit63 = "/_,")
    {
        if (digit >= 'A' && digit <= 'Z') return digit - 'A';
        if (digit >= 'a' && digit <= 'z') return digit + (26 - 'a');
        if (digit >= '0' && digit <= '9') return digit + (52 - '0');
        if (digit62.IndexOf(digit) > -1)  return 62;
        if (digit63.IndexOf(digit) > -1)  return 63;
        return -1;
    }
    
    public static char EncodeBase64Digit(int digit, char digit62 = '+', char digit63 = '/')
    {
        digit &= 63;
        if (digit < 52)
            return (char)(digit < 26 ? digit + 'A' : digit + ('a' - 26));
        else if (digit < 62)
            return (char)(digit + ('0' - 52));
        else
            return digit == 62 ? digit62 : digit63;
    }
    

    There are various versions of Base64 that disagree about what to use for digits 62 and 63, so DecodeBase64Digit can tolerate several of these.

提交回复
热议问题