如何转换为字节数组(MD5哈希值)到一个字符串(36个字符)?数组、字符串、转换为、字节

2023-09-03 04:06:14 作者:少年你这是喜脉

我有使用散列函数创建的字节数组。我想这个数组转换为字符串。到目前为止好,它会给我的十六进制字符串。

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.

现在我想用的东西的不同的比十六进制字符,我想EN code在字节数组这些 36个字符:[ AZ] [0-9] 。

Now I would like to use something different than hexadecimal characters, I would like to encode the byte array with these 36 characters: [a-z][0-9].

我会如何?

编辑:的我会做到这一点的原因,是因为我想有一个的小的字符串,不是一个十六进制字符串

the reason I would to do this, is because I would like to have a smaller string, than a hexadecimal string.

推荐答案

我从我的适应任意长度的基础转换功能this回答到C#:

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;
}

,因为它是从PHP它可能不会太地道的C#来了,也有不带参数有效性检查。但是,你可以给它一个十六进制恩codeD字符串,它会工作得很好用

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.