Base32 Decoding

后端 未结 7 652
遥遥无期
遥遥无期 2020-11-27 15:52

I have a base32 string which I need to convert to a byte array. And I\'m having trouble finding a conversion method in the .NET framework. I can find methods for base64 but

7条回答
  •  -上瘾入骨i
    2020-11-27 16:12

    Here are my functions for encoding and decoding. I feel that they are much shorter and concise than the other suggestions. So if you need a small one, try these.

    public static string BytesToBase32(byte[] bytes) {
        const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
        string output = "";
        for (int bitIndex = 0; bitIndex < bytes.Length * 8; bitIndex += 5) {
            int dualbyte = bytes[bitIndex / 8] << 8;
            if (bitIndex / 8 + 1 < bytes.Length)
                dualbyte |= bytes[bitIndex / 8 + 1];
            dualbyte = 0x1f & (dualbyte >> (16 - bitIndex % 8 - 5));
            output += alphabet[dualbyte];
        }
    
        return output;
    }
    
    public static byte[] Base32ToBytes(string base32) {
        const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
        List output = new List();
        char[] bytes = base32.ToCharArray();
        for (int bitIndex = 0; bitIndex < base32.Length * 5; bitIndex += 8) {
            int dualbyte = alphabet.IndexOf(bytes[bitIndex / 5]) << 10;
            if (bitIndex / 5 + 1 < bytes.Length)
                dualbyte |= alphabet.IndexOf(bytes[bitIndex / 5 + 1]) << 5;
            if (bitIndex / 5 + 2 < bytes.Length)
                dualbyte |= alphabet.IndexOf(bytes[bitIndex / 5 + 2]);
    
            dualbyte = 0xff & (dualbyte >> (15 - bitIndex % 5 - 8));
            output.Add((byte)(dualbyte));
        }
        return output.ToArray();
    }
    

提交回复
热议问题