如何获得C#中的十六进制值?
我正在使用一些传感器与串行通信。因为传感器数据有十六进制值,所以我应该将字符串数据转换为十六进制数据。因此,我使用的是如何获得C#中的十六进制值?,c#,string,hex,C#,String,Hex,我正在使用一些传感器与串行通信。因为传感器数据有十六进制值,所以我应该将字符串数据转换为十六进制数据。因此,我使用的是编码.Default.GetBytes(): 在本例中,存在一个问题-当值大于0x80时,传感器的转换值错误 比如说 74 61 85 0A FF 34 00 :: Original signal. 74 61 3F 0A 3F 34 00 :: Converted signal. 第五个字节不同。我不知道怎么了 string input = "Hello Wo
编码.Default.GetBytes()
:
在本例中,存在一个问题-当值大于0x80时,传感器的转换值错误
比如说
74 61 85 0A FF 34 00 :: Original signal.
74 61 3F 0A 3F 34 00 :: Converted signal.
第五个字节不同。我不知道怎么了
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
*/
资料来源:
从开始,数组
Bytdata0
和Bytdata1
是否包含相同的数据?从代码中看,它们似乎有不同的值:st.Substring(0,1)
用于Bytdata0
,st.Substring(1,1)
用于Bytdata1
。另外,我建议使用Encoding.UTF8.GetBytes(…)
,因为Encoding.Default
可能在不同的机器/操作系统上有所不同。我同意@IvayloSlavov的观点,st
的值是多少?谢谢你的回答。我发现了问题。这就是串行通信。在串行通信事件例程中,大于0x80的值表示为0x3F…但我还不知道原因。。。
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
*/
// 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);