网站系统维护一般要多久,python基础教程视频,购买网站广告位,wordpress 缺少临时文件夹咨询区 alextansc#xff1a;请问我如何实现将 byte[] 和 十六进制的string 进行互转#xff1f;回答区 balrob#xff1a;如果你的程序是基于 .NET5 的#xff0c;可以使用 Convert 下新增的两个方法 ToHexString 和 FromHexString #xff0c;参考下面两个方法的定义。/… 咨询区 alextansc请问我如何实现将 byte[] 和 十六进制的string 进行互转回答区 balrob如果你的程序是基于 .NET5 的可以使用 Convert 下新增的两个方法 ToHexString 和 FromHexString 参考下面两个方法的定义。//
// Summary:
// Converts an array of 8-bit unsigned integers to its equivalent string representation
// that is encoded with uppercase hex characters.
//
// Parameters:
// inArray:
// An array of 8-bit unsigned integers.
//
// Returns:
// The string representation in hex of the elements in inArray.
//
// Exceptions:
// T:System.ArgumentNullException:
// inArray is null.
//
// T:System.ArgumentOutOfRangeException:
// inArray is too large to be encoded.
public static string ToHexString(byte[] inArray);//
// Summary:
// Converts the specified string, which encodes binary data as hex characters, to
// an equivalent 8-bit unsigned integer array.
//
// Parameters:
// s:
// The string to convert.
//
// Returns:
// An array of 8-bit unsigned integers that is equivalent to s.
//
// Exceptions:
// T:System.ArgumentNullException:
// s is null.
//
// T:System.FormatException:
// The length of s, is not zero or a multiple of 2.
//
// T:System.FormatException:
// The format of s is invalid. s contains a non-hex character.
public static byte[] FromHexString(string s);Mykroft在 W3cXsd2001 命名空间下有一个可以实现 byte[] 到 hex 之间的转换方法我觉得可以满足你的需求参考如下using System.Runtime.Remoting.Metadata.W3cXsd2001;public static byte[] GetStringToBytes(string value)
{SoapHexBinary shb SoapHexBinary.Parse(value);return shb.Value;
}public static string GetBytesToString(byte[] value)
{SoapHexBinary shb new SoapHexBinary(value);return shb.ToString();
}Waleed Eissa我最近刚好也遇到了这个问题我是这么解决的。byte[] bytes {0, 1, 2, 4, 8, 16, 32, 64, 128, 256}
Console.WriteLine( BitConverter.ToString(bytes));但用它性能会比较慢所以基于它我做了一个版本优化性能是它的8倍以上参考如下private static string ByteArrayToHex(byte[] barray)
{char[] c new char[barray.Length * 2];byte b;for (int i 0; i barray.Length; i){b ((byte)(barray[i] 4));c[i * 2] (char)(b 9 ? b 0x37 : b 0x30);b ((byte)(barray[i] 0xF));c[i * 2 1] (char)(b 9 ? b 0x37 : b 0x30);}return new string(c);
}点评区 没想到 .NET5 中已经有了 FromHexStringToHexString 方法 Convert 类越来越强大了工作效率看样子又可以提高了。
相关文章: