1) 16进制字符串
a) c#内置apibyte[] 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(); }
参考 C# byte数组与16进制间的相互转换_Marydon的技术博客_51CTO博客 C# byte数组与16进制字符串相互转化 - 许宝 - 博客园 c# float转二进制 16进制 大端序小端序_将float类型转换为2字节的有符号16进制数-CSDN博客 标签:16,二进制,bytes,var,sb,byte,Append From: https://www.cnblogs.com/sailJs/p/18518143