Bytes to Hex

Hey I've been out of the C++ game for a long time now and trying to get back into it. I'm trying to start of with some basic stuff that can actually be useful to me as well. I'm trying to input bytes such as

14 A4 B7 54 85

and output it like this with comma separator

0x14, 0xA4, 0xB7, 0x54, 0x85

Any suggestions? Thanks
C++ streams can do this using std::hex.
As for output, you can do similar with std::showbase.
Yea i saw hex and showbase, but that will return the actual hex value of the input. What I'm doing is reading an applications memory and modifying bytes with my own bytes, but when you write it into the program it needs to be in 0x hex format if that makes any sense.
Last edited on
You can add the commas yourself. The idea is to use the stream manipulator to set the base, that's pretty much all you need.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <sstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>

int main()
{
    std::vector<int> values;
    std::string line = "14 A4 B7 54 85";

    std::istringstream is(line);
    int val;
    while (is >> std::hex >> val)
        values.push_back(val);

    for (auto val : values)
        std::cout << "0x" << std::hex << val << ' ';
    std::cout << "\n";
}
Hi,

One can use a delimiting char with the ostream iterator, have a look at the example at the end :+)

http://www.cplusplus.com/reference/iterator/ostream_iterator/


This isn't any better than kbw's code above, but it might come in handy some day :+)
Topic archived. No new replies allowed.