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

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

    System.Text.Encoding enc = System.Text.Encoding.ASCII;
    string myString = enc.GetString(myByteArray);
    

    You can play with what encoding you need:

    System.Text.ASCIIEncoding,
    System.Text.UnicodeEncoding,
    System.Text.UTF7Encoding,
    System.Text.UTF8Encoding
    

    To match the requrements [a-z][0-9] you can use it:

    Byte[] bytes = new Byte[] { 200, 180, 34 };
    string result = String.Join("a", bytes.Select(x => x.ToString()).ToArray());
    

    You will have string representation of bytes with char separator. To convert back you will need to split, and convert the string[] to byte[] using the same approach with .Select().

提交回复
热议问题