Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a buffer into a stringstream in hex representation:

If I had a buffer like:

uint8_t buffer[32]; 

and it was filled up completely with values, how could I get it into a stringstream, in hexadecimal representation, with 0-padding on small values?

I tried:

std::stringstream ss; for (int i = 0; i < 32; ++i) {     ss << std::hex << buffer[i]; } 

but when I take the string out of the stringstream, I have an issue: bytes with values < 16 only take one character to represent, and I'd like them to be 0 padded.

For example if bytes 1 and 2 in the array were {32} {4} my stringstream would have:

204 instead of 2004 

Can I apply formatting to the stringstream to add the 0-padding somehow? I know I can do this with sprintf, but the streams already being used for a lot of information and it would be a great help to achieve this somehow.

like image 799
John Humphreys Avatar asked Oct 03 '11 19:10

John Humphreys


People also ask

Does Stringstream allocate?

stringstream is constructed with dummy. This copies the entire string's contents into an internal buffer, which is preallocated. dummy is then cleared and then erased, freeing up its allocation.

Why is Stringstream slow?

stringstreams are primarily there for convenience and type-safety, not speed. The stream will collect the input and then eventually call strtold for the conversion. Makes it hard to be any faster!

How do you flush a Stringstream?

Use the str("") and the clear() Method to Clear stringstream in C++ To clear out or empty stringstream , we can use the str("") and clear() method, but we have to use both the methods; else the program might not work properly, i.e., it won't give the correct output.

What is CPP Stringstream?

The stringstream class in C++ allows a string object to be treated as a stream. It is used to operate on strings. By treating the strings as streams we can perform extraction and insertion operation from/to string just like cin and cout streams.


1 Answers

#include <sstream> #include <iomanip>  std::stringstream ss; ss << std::hex << std::setfill('0'); for (int i = 0; i < 32; ++i) {     ss << std::setw(2) << static_cast<unsigned>(buffer[i]); } 
like image 173
Dean Povey Avatar answered Sep 26 '22 00:09

Dean Povey