2014-01-06 36 views
1

我正在使用一些傳感器與串行通信。由於傳感器數據具有HEX值,因此我應該將字符串數據轉換爲十六進制數據。所以,我使用Encoding.Default.GetBytes()如何獲取C#中的十六進制值?

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. 

第五字節不同。我不知道什麼是錯的。

+2

是陣列'Bytdata0'和'Bytdata1'包含相同數據?形成你的代碼,它們看起來有不同的值:'st.Substring(0,1)'用於'Bytdata0','st.Substring(1,1)'用於'Bytdata1'。另外,我建議使用'Encoding.UTF8.GetBytes(...)',因爲'Encoding.Default'可以在不同的機器/操作系統上有所不同。 –

+1

我同意@IvayloSlavov,'st'的價值是什麼? – paqogomez

+0

感謝您的回答。我發現了這個問題。那就是串行通信。在串行通信事件例程中,值大於0x80的值表示爲0x3F ....但我不知道原因... – user3164483

回答

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

SOURCE: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

相關問題