Convert binary hex data to ASCII equivalent and store in String

我与影子孤独终老i 提交于 2019-12-12 01:37:08

问题


I am using C++ on Arduino.

Suppose I have a stream of binary data;

binary data: 0xFF, 0x00, 0x01, 0xCC

I want to convert it to the ASCII equivalent and store it in a String object type.

The converted string should look like this "FF0001CC".

Here are some draft code.

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

The problem with this code is that myString contains FF01CC, not FF0001CC.


回答1:


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



回答2:


There is stringstream class available in C++, it may be usable in this case. With C three bytes would be printed to a buffer with one sprintf-statement sprintf(buffer, "%02x%02x%02x", bytes[0], bytes[1], bytes[2]) (preferably snprintf).

#include <sstream>
#include <iostream>
#include <iomanip>

int main(void)
{
    std::stringstream ss;
    unsigned char bytes[] = {0xff, 0x00, 0xcc};

    ss << std::hex;

    // This did not work, 00 was printed as 0
    // ss << std::setfill('0') << std::setw(2)
    // ...
    // ss << (unsigned int)bytes[i]

    for (int i=0; i<3; i++) {
       unsigned int tmp = bytes[i];
       ss << (tmp >> 4) << (tmp & 0xf);
    }
    std::cout << ss.str();

    return 0;
}



回答3:


As understand numBytes can be bigger than 3 or 4 (otherwise why buffer size is 100?) Also I prefer to use C++ classes when working with string (you need string, not char[]?).

Consider the following example with stringstream class (just include sstream and iomanip standard headers):

    string myString;
    stringstream myStringStream;
    myStringStream << setbase(16);
    myStringStream << uppercase;
    for (int i = 0; i < numBytes; i++)
    {
        myStringStream << (0xFF & (unsigned int) buffer[i]);
    }
    myString = myStringStream.str();

I can not compare the speed of my example with other answers, but this solution is really C++ approach for buffer of any size.



来源:https://stackoverflow.com/questions/34782709/convert-binary-hex-data-to-ascii-equivalent-and-store-in-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!