将二进制十六进制数据转换为 ASCII 等价物并存储在字符串中 [英] Convert binary hex data to ASCII equivalent and store in String
问题描述
我在 Arduino 上使用 C++.
I am using C++ on Arduino.
假设我有一个二进制数据流;
Suppose I have a stream of binary data;
二进制数据:0xFF, 0x00, 0x01, 0xCC
我想将其转换为等效的 ASCII 并将其存储在 String 对象类型中.
I want to convert it to the ASCII equivalent and store it in a String object type.
转换后的字符串应类似于FF0001CC".
The converted string should look like this "FF0001CC".
这里是一些草稿代码.
char buffer[100];
String myString;
for (int i=0; i < numBytes; i++)
{
//assume buffer contains some binary data at this point
myString += String(buffer[i], HEX);
}
此代码的问题在于 myString
包含 FF01CC
,而不是 FF0001CC
.
The problem with this code is that myString
contains FF01CC
, not FF0001CC
.
推荐答案
我的猜测是每次附加文本时 String 类都会调整大小,这可以改进.假设你知道输入大小并且它是常数,你可以试试这个:
My guess would be that the String class resizes each time a text is appended, that could be improved. Assuming you know the input size and it´s constant, you could try this:
char outbuffer[numBytes*2+1];
const char* pHexTable="0123456789ABCDEF";
int iPos=0;
for(int i=0; i<numBytes; i++){
//assume buffer contains some binary data at this point
const char cHex=buffer[i];
outbuffer[iPos++]=pHexTable[(cHex>>4)&0x0f];
outbuffer[iPos++]=pHexTable[cHex&0x0f];
}
outbuffer[iPos]='\0';
这篇关于将二进制十六进制数据转换为 ASCII 等价物并存储在字符串中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!