Reputation: 190979
With the help of this site, C++ int to byte array, I have a code to serialize int to byte stream.
The byte stream data from integer value 1234 is '\x00\x00\x04\xd2' in big endian format, and I need to come up with an utility function to display the byte stream. This is my first version.
#include <iostream>
#include <vector>
using namespace std;
std::vector<unsigned char> intToBytes(int value)
{
std::vector<unsigned char> result;
result.push_back(value >> 24);
result.push_back(value >> 16);
result.push_back(value >> 8);
result.push_back(value );
return result;
}
void print(const std::vector<unsigned char> input)
{
for (auto val : input)
cout << val; // <--
}
int main(int argc, char *argv[]) {
std::vector<unsigned char> st(intToBytes(1234));
print(st);
}
How can I get correct value on the screen both in decimal and hex?
Upvotes: 3
Views: 17660
Reputation: 11058
For hex:
for (auto val : input) printf("\\x%.2x", val);
For decimal:
for (auto val : input) printf("%d ", val);
Upvotes: 13