简体   繁体   English

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

[英]How can I get the hex value in C#?

I am using some sensor with Serial Communication. 我正在通过串行通信使用某些传感器。 Because the sensor data have HEX value, I should convert string data to hex data. 因为传感器数据具有十六进制值,所以我应该将字符串数据转换为十六进制数据。 So, I am using Encoding.Default.GetBytes() : 所以,我正在使用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);

In this example, there is a problem - the converted value of sensor is wrong when the value is bigger than 0x80. 在此示例中,存在一个问题-当该值大于0x80时,传感器的转换值是错误的。

For example 例如

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

the fifth bytes differ. 第五个字节不同。 I don't know what is wrong. 我不知道怎么了

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

SOURCE: http://msdn.microsoft.com/en-us/library/bb311038.aspx 消息来源: 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);

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM