简体   繁体   中英

How do I convert the decimal value in hex string and hex string and hex string to byte

I have bytes array of decimal values like [0, 4, 20, 141] and I want that to be converted as [0x00, 0x04, 0x14, 0x8D] which I need to use this array as bytes to add in a buffer

Current data:

byte[] packet = new byte[4];

packet[0] = 0;
packet[1] = 4;
packet[2] = 20;
packet[3] = 141;

and expected data to send to the serial port is as below:

byte[] mBuffer = new byte[4];

mBuffer[0] = 0x02;
mBuffer[1] = 0x04;
mBuffer[2] = 0x14;
mBuffer[3] = 0x8D;

Tried:

Convert.ToByte(string.Format("{0:X}", packet[0]));

But throwing an exception:

Input string was not in a correct format.

You're getting the exception because you're trying to substitute a variable in the string without the "$" prefix. Try this:

// Converts integer 141 to string "8D"
String parsed = String.Format($"{0:X}", packet[3]);  

Then, you should be able to convert to a byte using this:

// Parses string "8D" as a hex number, resulting in byte 0x8D (which is 141 in decimal)
Byte asByte = Byte.Parse(parsed, NumberStyles.HexNumber); 

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