⼗六进制字符串与数值类型之间转换
string input = "Hello World!"; char[] values = input.ToCharArray(); foreach (char letter in values) { // Get the integral value of the character. int value = Convert.ToInt32(letter); // Convert the integer value to a hexadecimal value in string form. Console.WriteLine($"Hexadecimal value of {letter} is {value:X}"); }
string hexValues = "48 65 6C 6C 6F 20 57 6F 72 6C 64 21"; string[] hexValuesSplit = hexValues.Split(' '); foreach (string hex in hexValuesSplit) { // Convert the number expressed in base-16 to an integer. int value = Convert.ToInt32(hex, 16); // Get the character corresponding to the integral value. string stringValue = Char.ConvertFromUtf32(value); char charValue = (char)value; Console.WriteLine("hexadecimal value = {0}, int value = {1}, char value = {2} or {3}", hex, value, stringValue, charValue); }
此示例演示了将十六进制 string 转换为整数的另一种方法,即调用 Parse(String, NumberStyles) 方法。
string hexString = "8E2"; int num = Int32.Parse(hexString, System.Globalization.NumberStyles.HexNumber); Console.WriteLine(num); //Output: 2274
下面的示例演示了如何使用 System.BitConverter 类和 UInt32.Parse 方法将十六进制 string 转换为 float。
string hexString = "43480170"; uint num = uint.Parse(hexString, System.Globalization.NumberStyles.AllowHexSpecifier); byte[] floatVals = BitConverter.GetBytes(num); float f = BitConverter.ToSingle(floatVals, 0); Console.WriteLine("float convert = {0}", f); // Output: 200.0056
下面的示例演示了如何使用 System.BitConverter 类将字节数组转换为十六进制字符串。
byte[] vals = { 0x01, 0xAA, 0xB1, 0xDC, 0x10, 0xDD }; string str = BitConverter.ToString(vals); Console.WriteLine(str); str = BitConverter.ToString(vals).Replace("-", ""); Console.WriteLine(str); /*Output: 01-AA-B1-DC-10-DD 01AAB1DC10DD */
下面的示例演示如何通过调用 .NET 5.0 中引入的 Convert.ToHexString 方法,将字节数组转换为十六进制字符 串。
byte[] array = { 0x64, 0x6f, 0x74, 0x63, 0x65, 0x74 }; string hexValue = Convert.ToHexString(array); Console.WriteLine(hexValue); /*Output: 646F74636574 */