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
.
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])
(preferablysnprintf
).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:
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 withstring
(you needstring
, notchar[]
?).Consider the following example with
stringstream
class (just includesstream
andiomanip
standard headers):I can not compare the speed of my example with other answers, but this solution is really C++ approach for
buffer
of any size.