简体   繁体   English

如何将十六进制字符串,十六进制字符串和十六进制字符串中的十进制值转换为字节

[英]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 我有十进制值的字节数组,例如[0, 4, 20, 141] [0x00, 0x04, 0x14, 0x8D] ,我希望将其转换为[0x00, 0x04, 0x14, 0x8D] ,我需要将此数组用作字节以添加到缓冲区中

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); 

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

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