在C#中将string转换为hexstring

我有一个像“样本”的string。 我想要得到一个hex格式的string; 喜欢这个:

"796173767265" 

请给C#语法。

首先你需要把它放到一个byte[] ,所以这样做:

 byte[] ba = Encoding.Default.GetBytes("sample"); 

然后你可以得到string:

 var hexString = BitConverter.ToString(ba); 

现在,这将返回一个带有破折号( - )的string,所以你可以简单地使用这个:

 hexString = hexString.Replace("-", ""); 

如果你想要摆脱那些。

注意:如果需要,可以使用不同的Encoding

 var result = string.Join("", input.Select(c => ((int)c).ToString("X2"))); 

要么

 var result =string.Join("", input.Select(c=> String.Format("{0:X2}", Convert.ToInt32(c)))); 

对于Unicode支持:

 public class HexadecimalEncoding { public static string ToHexString(string str) { var sb = new StringBuilder(); var bytes = Encoding.Unicode.GetBytes(str); foreach (var t in bytes) { sb.Append(t.ToString("X2")); } return sb.ToString(); // returns: "48656C6C6F20776F726C64" for "Hello world" } public static string FromHexString(string hexString) { var bytes = new byte[hexString.Length / 2]; for (var i = 0; i < bytes.Length; i++) { bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16); } return Encoding.Unicode.GetString(bytes); // returns: "Hello world" for "48656C6C6F20776F726C64" } } 

根据这个片段,这个方法应该适用于长string:

 private string StringToHex(string hexstring) { StringBuilder sb = new StringBuilder(); foreach (char t in hexstring) { //Note: X for upper, x for lower case letters sb.Append(Convert.ToInt32(t).ToString("x")); } return sb.ToString(); } 

用法:

 string result = StringToHex("Hello world"); //returns "48656c6c6f20776f726c64" 

另一种方法在一条线上

 string input = "Hello world"; string result = String.Concat(input.Select(x => ((int)x).ToString("x"))); 

几个Unicode的替代品

 var s = "0𝟏𝟚𝟥𝟰𝟻"; var s1 = s.Aggregate("", (h, c) => h + ((int)c).ToString("x4")); // left padded with 0 "0030d835dfcfd835dfdad835dfe5d835dff0d835dffb" var s2 = s.Aggregate("", (h, c) => h + string.Format("{0,4:x}", (int)c)); // left padded with space " 30d835dfcfd835dfdad835dfe5d835dff0d835dffb" var sL = BitConverter.ToString(Encoding.Unicode.GetBytes(s)).Replace("-", ""); // Little Endian "300035D8CFDF35D8DADF35D8E5DF35D8F0DF35D8FBDF" var sB = BitConverter.ToString(Encoding.BigEndianUnicode.GetBytes(s)).Replace("-", ""); // Big Endian "0030D835DFCFD835DFDAD835DFE5D835DFF0D835DFFB" // no encodding "300035D8CFDF35D8DADF35D8E5DF35D8F0DF35D8FBDF" byte[] b = new byte[s.Length * sizeof(char)]; Buffer.BlockCopy(s.ToCharArray(), 0, b, 0, b.Length); var sb = BitConverter.ToString(b).Replace("-", "");