[英]Convert String to HEX on arduino platform
I am doing a small parser that should convert a string into an Hexadecimal value,I am using arduino as platform but I am getting stack with it. 我正在做一个小型解析器,应该将字符串转换为十六进制值,我使用arduino作为平台,但是我正在与它堆叠。
My string is data = "5449"
where each element is an char, so I would like to translate it to a HEX value like dataHex = 0x54 0x59
, and finally those values should be translate to ASCII as dataAscii= TI
我的字符串是
data = "5449"
,其中每个元素都是一个字符,因此我想将其转换为十六进制值,如dataHex = 0x54 0x59
,最后将这些值转换为ASCII,即dataAscii= TI
How can I do this? 我怎样才能做到这一点?
I was thinking of splitting it into an char array with dataCharArray = 54 49
and later converting those values to the chars T and I, but I am not sure whether or not that is the best way. 我当时正在考虑将其拆分为
dataCharArray = 54 49
的char数组,然后将这些值转换为char T和I,但是我不确定这是否是最佳方法。
Thanks in advance, 提前致谢,
regards! 问候!
I don't have arduino installed in my PC right now, so let's hope the following works: 我的电脑上现在没有安装arduino,因此希望以下工作:
char nibble2c(char c)
{
if ((c>='0') && (c<='9'))
return c-'0' ;
if ((c>='A') && (c<='F'))
return c+10-'A' ;
if ((c>='a') && (c<='a'))
return c+10-'a' ;
return -1 ;
}
char hex2c(char c1, char c2)
{
if(nibble2c(c2) >= 0)
return nibble2c(c1)*16+nibble2c(c2) ;
return nibble2c(c1) ;
}
String hex2str(char *data)
{
String result = "" ;
for (int i=0 ; nibble2c(data[i])>=0 ; i++)
{
result += hex2c(data[i],data[i+1]) ;
if(nibble2c(data[i+1])>=0)
i++ ;
}
return result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.