How to convert a byte array (MD5 hash) into a string (36 chars)?

后端 未结 7 1954
走了就别回头了
走了就别回头了 2021-01-14 01:18

I\'ve got a byte array that was created using a hash function. I would like to convert this array into a string. So far so good, it will give me hexadecimal string.

相关标签:
7条回答
  • 2021-01-14 02:05

    I adapted my arbitrary-length base conversion function from this answer to C#:

    static string BaseConvert(string number, int fromBase, int toBase)
    {
        var digits = "0123456789abcdefghijklmnopqrstuvwxyz";
        var length = number.Length;
        var result = string.Empty;
    
        var nibbles = number.Select(c => digits.IndexOf(c)).ToList();
        int newlen;
        do {
            var value = 0;
            newlen = 0;
    
            for (var i = 0; i < length; ++i) {
                value = value * fromBase + nibbles[i];
                if (value >= toBase) {
                    if (newlen == nibbles.Count) {
                        nibbles.Add(0);
                    }
                    nibbles[newlen++] = value / toBase;
                    value %= toBase;
                }
                else if (newlen > 0) {
                    if (newlen == nibbles.Count) {
                        nibbles.Add(0);
                    }
                    nibbles[newlen++] = 0;
                }
            }
            length = newlen;
            result = digits[value] + result; //
        }
        while (newlen != 0);
    
        return result;
    }
    

    As it's coming from PHP it might not be too idiomatic C#, there are also no parameter validity checks. However, you can feed it a hex-encoded string and it will work just fine with

    var result = BaseConvert(hexEncoded, 16, 36);
    

    It's not exactly what you asked for, but encoding the byte[] into hex is trivial.

    See it in action.

    0 讨论(0)
提交回复
热议问题