将十六进制的字符串表示形式转换为字节的最佳方法? (与 Arduino 一起工作)

问题描述 投票:0回答:0

我正在通过串行端口发送字节的十六进制表示形式,我需要将其转换为字节以在我的应用程序中使用。我已经用几种不同的方法来处理它,看起来必须有一种比我以前更容易处理它的方法(而且我还没有在网上找到任何可以解决这个问题的方法)。我猜可能有一个简单的函数可以完成我想要它做的事情而无需 3 或 4 种不同的转换。

有人对如何解决这个问题有什么建议吗?

本质上,我试图获取一个值为“CE”的字符串 (inString),并将等效的字节形式(0xCE 或 206)存储到 outByte 中。以下是我目前正在使用的:

原码:

String inString = “CE”
Byte outByte;
outByte = inString.toInt();
printData("outByte: " + String(outByte),serialchan);

输出:

outByte: 0

其他方法:

String inString = “CE”
Byte outByte;

char tempchar[2];
String tempstring;
inString.toCharArray(tempchar, 4); // Works with 4, not with 2 for whatever reason
printData("inString: " + String(inString),serialchan);
printData("inString hex: " + String(tempchar),serialchan);

tempstring = "0x" + String(inString);
printData("inString in string hex: " + String(tempstring),serialchan);
outByte = (byte)tempstring.toInt();
printData("outByte: " + String(outByte),serialchan);

输出:

outByte: 0                                                        
inString: CE                                                   
inString hex: CE                                                
inString in string hex: 0xCE                                     
outByte: 0

我希望 outByte 读取 206(稍后我会将其转换为十六进制字符串,我猜这很简单)。就像我说的,我想我很接近。 . .但似乎应该有一个简单的一两行解决方案。如果您有任何建议,请让我知道。谢谢!

c string arduino byte
© www.soinside.com 2019 - 2024. All rights reserved.