简体   繁体   中英

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() :

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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