Getting Correct Hex Format

I'm trying to get the hex values from file data that I imported into a character buffer. I use a stringstream to convert each char to a hex string but it is not in the format that I want.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;

int main()
{
    ifstream infile;
    infile.open("clock.png", ifstream::binary);
    
    int length;
    infile.seekg(0, ifstream::end);
    length = infile.tellg();
    infile.seekg(0, ifstream::beg);
    
    char data1[length];
    
    infile.read(data1, length);
    infile.close();
    
    string data2[length];
    
    for (int x = 0; x < length; x++)
    {
        stringstream ss;
        ss << hex << (int)data1[x];
        data2[x] = "0x";
        data2[x] += ss.str();
        cout << data2[x] << endl;
    }
    
    return 0;
}


This is the output:
...
0x16
0xffffffa6
0x0
0x0
0x0
0x0
0x49
0x45
0x4e
0x44
0xffffffae
0x42
0x60
0xffffff82
...


My question is how to convert "ffffffae" to "ae" and "0" to "00". I guess I could just go through each string individually and add/remove the characters, but isn't there a better way?

----- EDIT -----

Got it! Thanks to GeneralZod at the Ubuntu forums:

1
2
3
4
5
6
7
8
9
10
11
#include <iomanip>
.....

    for (int x = 0; x < length; x++)
    {
        stringstream ss;
        ss << "0x" << hex << setw(2) << setfill('0') << (int)(unsigned char)data1[x];
        data2[x] += ss.str();
        cout << data2[x] << endl;
    }
.....
Last edited on
Topic archived. No new replies allowed.