此示例输出 string 中的每个字符的十六进制值。
首先,它将 string 分析为字符数组,然后对每个字符调用 ToInt32(Char) 以获取相应的数字值。最后,在 string 中将数字的格式设置为十六进制表示形式。
C#
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 decimal value to a hexadecimal value in string form.
string hexOutput = String.Format("{0:X}", value);
Console.WriteLine("Hexadecimal value of {0} is {1}", letter, hexOutput);}
/* Output:
Hexadecimal value of H is 48
Hexadecimal value of e is 65
Hexadecimal value of l is 6C
Hexadecimal value of l is 6C
Hexadecimal value of o is 6F
Hexadecimal value of is 20
Hexadecimal value of W is 57
Hexadecimal value of o is 6F
Hexadecimal value of r is 72
Hexadecimal value of l is 6C
Hexadecimal value of d is 64
Hexadecimal value of ! is 21 */
此示例分析十六进制值的 string 并输出对应于每个十六进制值的字符。
首先,它调用 Split(Char[]) 方法以获取每个十六进制值作为数组中的单个 string。然后调用 ToInt32(String, Int32) 以将十六进制转换为表示为 int 的十进制值。示例中演示了用于获取对应于该字符代码的字符的两种不同方法。第一种方法是使用 ConvertFromUtf32(Int32),它将对应于整型参数的字符作为 string 返回。第二种方法是将 int 显式转换为 char。
C#
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);
}
/* Output:
hexadecimal value = 48, int value = 72, char value = H or H
hexadecimal value = 65, int value = 101, char value = e or e
hexadecimal value = 6C, int value = 108, char value = l or l
hexadecimal value = 6C, int value = 108, char value = l or l
hexadecimal value = 6F, int value = 111, char value = o or o
hexadecimal value = 20, int value = 32, char value = or
hexadecimal value = 57, int value = 87, char value = W or W
hexadecimal value = 6F, int value = 111, char value = o or o
hexadecimal value = 72, int value = 114, char value = r or r
hexadecimal value = 6C, int value = 108, char value = l or l
hexadecimal value = 64, int value = 100, char value = d or d
hexadecimal value = 21, int value = 33, char value = ! or !
*/
此示例演示了将十六进制 string 转换为整数的另一种方法,即调用 Parse(String, NumberStyles) 方法。
C#
string hexString = "8E2";
int num = Int32.Parse(hexString, System.Globalization.NumberStyles.HexNumber);
Console.WriteLine(num);
//Output: 2274
下面的示例演示如何使用 System.BitConverter 类和 Int32.Parse 方法将十六进制 string 转换为浮点型。
C#
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
2.十六进制字符串转byte[]/byte[]转十六进制字符串
- /// <summary>
- /// 16进制字符串转字节数组
- /// </summary>
- /// <param name="hexString"></param>
- /// <returns></returns>
- private static byte[] strToToHexByte(string hexString)
- {
- hexString = hexString.Replace(" ", "");
- if ((hexString.Length % 2) != 0)
- hexString += " ";
- byte[] returnBytes = new byte[hexString.Length / 2];
- for (int i = 0; i < returnBytes.Length; i++)
- returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Trim(), 16);
- return returnBytes;
- }
- /// <summary>
- /// 字节数组转16进制字符串
- /// </summary>
- /// <param name="bytes"></param>
- /// <returns></returns>
- public static string byteToHexStr(byte[] bytes)
- {
- string returnStr = "";
- if (bytes != null)
- {
- for (int i = 0; i < bytes.Length; i++)
- {
- returnStr += bytes[i].ToString("X2");
- }
- }
- return returnStr;
- }
另外,更简单的
byte[] 转十六进制字符串还可以利用BitConverter.ToString方法,这个更容易使用。
string str0x = BitConverter.ToString(byte[] tyt,0,length);
返回的字符串是带“-”分离的十六进制字符串,可以去掉:
string str0x = BitConverter.ToString(byte[] tyt,0,recv).Replace("-", "");
BitConverter类提供基础数据类型与字节数组相互转换的方法。
- /// <summary>
- /// 从汉字转换到16进制
- // </summary>
- /// <param name="s"></param>
- /// <param name="charset">编码,如"utf-8","gb2312"</param>
- /// <param name="fenge">是否每字符用逗号分隔</param>
- /// <returns></returns>
- public static string ToHex(string s, string charset, bool fenge)
- {
- if ((s.Length % 2) != 0)
- {
- s += " ";//空格
- //throw new ArgumentException("s is not valid chinese string!");
- }
- System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);
- byte[] bytes = chs.GetBytes(s);
- string str = "";
- for (int i = 0; i < bytes.Length; i++)
- {
- str += string.Format("{0:X}", bytes[i]);
- if (fenge && (i != bytes.Length - 1))
- {
- str += string.Format("{0}", ",");
- }
- }
- return str.ToLower();
- }
- /// <summary>
- /// 从16进制转换成汉字
- /// </summary>
- /// <param name="hex"></param>
- /// <param name="charset">编码,如"utf-8","gb2312"</param>
- /// <returns></returns>
- public static string UnHex(string hex, string charset)
- {
- if (hex == null)
- throw new ArgumentNullException("hex");
- hex = hex.Replace(",", "");
- hex = hex.Replace("\n", "");
- hex = hex.Replace("\\", "");
- hex = hex.Replace(" ", "");
- if (hex.Length % 2 != 0)
- {
- hex += "20";//空格
- }
- // 需要将 hex 转换成 byte 数组。
- byte[] bytes = new byte[hex.Length / 2];
- for (int i = 0; i < bytes.Length; i++)
- {
- try
- {
- // 每两个字符是一个 byte。
- bytes[i] = byte.Parse(hex.Substring(i * 2, 2),
- System.Globalization.NumberStyles.HexNumber);
- }
- catch
- {
- // Rethrow an exception with custom message.
- throw new ArgumentException("hex is not a valid hex number!", "hex");
- }
- }
- System.Text.Encoding chs = System.Text.Encoding.GetEncoding(charset);
- return chs.GetString(bytes);
- }