简体   繁体   中英

In C#, how do I convert an array of bytes into a string of hex numbers?

在C#中,将字节数组转换为十六进制数字字符串的最简洁方法是什么?

BitConverter.ToString http://msdn.microsoft.com/en-us/library/system.bitconverter.tostring.aspx

You'll get hyphens between bytes in the string, but they are easily removed.

This should work... BitConverter is better, but this gives you more control (no hyphens) and you can get fancy with lambdas if you so wished :)

 public string byteToHex(byte[] byteArray) {
    StringBuilder result = new StringBuilder();
    foreach (byte b in byteArray) {
        result.AppendString(b.ToString("X2"));
    }
    return result.ToString();
 }

Here's an extension I use when I need lowercase hex. eg Facebook requires lowercase for signing POST data.

    private static string ToLowerCaseHexString(this IEnumerable<byte> hash)
    {
        return hash
            .Select(b => String.Format("{0:x2}",
                                       b))
            .Aggregate((a, b) => a + b);
    }

Might be quicker using a StringBuilder over linq .Aggregate, but the byte arrays I pass are short.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM