如何在C#中获取十六进制值?

时间:2014-01-06 07:18:49

标签: c# string hex

我正在使用一些带串行通信的传感器。因为传感器数据具有HEX值,所以我应该将字符串数据转换为十六进制数据。所以,我正在使用Encoding.Default.GetBytes()

byte[] Bytdata0 = Encoding.Default.GetBytes(st.Substring(0, 1));
byte[] Bytdata1 = Encoding.Default.GetBytes(st.Substring(1, 1));

foreach (byte byte_str in Bytdata0) Whole_data[0] = string.Format("{0:X2}", byte_str);
foreach (byte byte_str in Bytdata1) Whole_data[1] = string.Format("{0:X2}", byte_str);

在这个例子中,存在一个问题 - 当值大于0x80时,传感器的转换值是错误的。

例如

74 61 85 0A FF 34 00     :: Original signal.
74 61 3F 0A 3F 34 00     :: Converted signal.

第五个字节不同。我不知道出了什么问题。

1 个答案:

答案 0 :(得分:1)

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
 */

消息来源:http://msdn.microsoft.com/en-us/library/bb311038.aspx

// Store integer 182
int decValue = 182;
// Convert integer 182 as a hex in a string variable
string hexValue = decValue.ToString("X");
// Convert the hex string back to the number
int decAgain = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);

来自http://www.geekpedia.com/KB8_How-do-I-convert-from-decimal-to-hex-and-hex-to-decimal.html