byte数组转16进制,二进制字符串

1) 16进制字符串

a) c#内置api
byte[] bytes = BitConverter.GetBytes(123);
var hexStr = BitConverter.ToString(bytes);

 

b) 实现1

///返回低字节顺序十六进制字符串(低字节在左侧)
public static string ToHexString(byte[] bytes)
{
    char[] hexChars = "0123456789ABCDEF".ToCharArray();
    var sb = new StringBuilder();
    foreach (var b in bytes)
    {
        char c1 = hexChars[b >> 4];
        char c2 = hexChars[b & 0x0f];
        sb.Append(c1).Append(c2).Append('-');
    }
    sb.Remove(sb.Length - 1, 1);
    return sb.ToString();
}

 

c) 实现2

public static string ToHexString2(byte[] bytes)
{
    var sb = new StringBuilder();
    foreach (var b in bytes)
    {
        sb.Append(Convert.ToString(b, 16).PadLeft(2, '0')).Append('-');
    }
    sb.Remove(sb.Length - 1, 1);
    return sb.ToString();
}

 

 2) 二进制字符串

///返回高字节顺序的二进制字符串(高字节在左)

public static string ToBinString(byte[] bytes)
{
    var sb = new StringBuilder();
    if (BitConverter.IsLittleEndian)
    {
        //小端时: bytes数组顺序为低字节 -> 高字节,所以要反向遍历
        for (int i = bytes.Length - 1; i >= 0; --i)
        {
            byte b = bytes[i];
            var byteBin = Convert.ToString(b, 2).PadLeft(8, '0');
            sb.Append(byteBin).Append(' ');
        }
    }
    else
    {
        //大端时: bytes数组顺序为高字节 -> 低字节
        foreach (var b in bytes)
        {
            var byteBin = Convert.ToString(b, 2).PadLeft(8, '0');
            sb.Append(byteBin).Append(' ');
        }
    }
    sb.Remove(sb.Length - 1, 1);
    return sb.ToString();
}

 

参考
 
posted @ 2024-11-08 22:41  yanghui01  阅读(5)  评论(0编辑  收藏  举报