简体   繁体   English

将十六进制字符串字节转换为字节数组

[英]Convert hexadecimal string byte into byte array

I am building a client application which needs to send packet to server in a particular format such that if the byte is 0xA3, the server expects it as {0x3A, 0x33} 我正在构建一个客户端应用程序,该应用程序需要以特定格式将数据包发送到服务器,以便如果字节为0xA3,则服务器期望它为{0x3A,0x33}

I had used the below approach earlier. 我之前使用过以下方法。 It works well if the byte is for instance 0x89. 如果该字节是例如0x89,则效果很好。 But if the byte is 0xA3 it doesnt work 但是,如果字节是0xA3,它将不起作用

string hex = hexStr .Length == 1 ? "0" + hexStr:hexStr ;
byte packet1 = (byte)(int.Parse(hex[0].ToString(), System.Globalization.NumberStyles.HexNumber) + 0x30);
byte packet2 = (byte)(int.Parse(hex[1].ToString(), System.Globalization.NumberStyles.HexNumber) + 0x30);

Examples of expected output 预期输出示例

  1. input => 0x89 , Output => {0x38, 0x39} 输入=> 0x89,输出=> {0x38,0x39}
  2. input => 0xA3 , Output => {0x3A, 0x33} 输入=> 0xA3,输出=> {0x3A,0x33}

However if i use the above code i get the following output 但是,如果我使用上面的代码,则会得到以下输出

  1. input => 0x89 , Output => {0x38, 0x39} 输入=> 0x89,输出=> {0x38,0x39}
  2. input => 0xA3 , Output => {0x41, 0x33} 输入=> 0xA3,输出=> {0x41,0x33}

The problem isn't in the code you've shown. 问题不在您显示的代码中。

You need to do all your math in hexadecimal, and convert to strings (if needed) into hexadecimal as well: 您需要使用十六进制进行所有数学运算,并将字符串(如果需要)也转换为十六进制:

string hex = "A3";
byte packet1 = (byte)(int.Parse(hex[0].ToString(), NumberStyles.HexNumber) + 0x30);
byte packet2 = (byte)(int.Parse(hex[1].ToString(), NumberStyles.HexNumber) + 0x30);

Console.WriteLine("{0:X2}, {1:X2}", packet1, packet2); // 3A, 33

works exactly as you expect. 完全按照您的预期工作。

The results you got seem to indicate that you took 30 (decimal), added 0xA (11), and printed as decimal, rather than hexa-decimal. 您得到的结果似乎表明您使用了30 (十进制),加上了0xA (11),并以十进制而不是十六进制打印。 This does not happen in the code you've posted, so just fix your actual code and you'll be fine. 在您发布的代码中不会发生这种情况,因此只需修正您的实际代码即可。

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

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