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

后端 未结 7 1956
走了就别回头了
走了就别回头了 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 01:49

    you can use modulu. this example encode your byte array to string of [0-9][a-z]. change it if you want.

        public string byteToString(byte[] byteArr)
        {
            int i;
            char[] charArr = new char[byteArr.Length];
            for (i = 0; i < byteArr.Length; i++)
            {
                int byt = byteArr[i] % 36; // 36=num of availible charachters
                if (byt < 10)
                {
                    charArr[i] = (char)(byt + 48); //if % result is a digit
                }
                else
                {
                    charArr[i] = (char)(byt + 87); //if % result is a letter
                }
            }
            return new String(charArr);
        }
    

    If you don't want to lose data for de-encoding you can use this example:

        public string byteToString(byte[] byteArr)
        {
            int i;
            char[] charArr = new char[byteArr.Length*2];
            for (i = 0; i < byteArr.Length; i++)
            {
                charArr[2 * i] = (char)((int)byteArr[i] / 36+48);
                int byt = byteArr[i] % 36; // 36=num of availible charachters
                if (byt < 10)
                {
                    charArr[2*i+1] = (char)(byt + 48); //if % result is a digit
                }
                else
                {
                    charArr[2*i+1] = (char)(byt + 87); //if % result is a letter
                }
            }
            return new String(charArr);
        }
    

    and now you have a string double-lengthed when odd char is the multiply of 36 and even char is the residu. for example: 200=36*5+20 => "5k".

提交回复
热议问题