c++ convert string to uint8_t array and back

2.8k views Asked by At

I'm trying to convert a string into an uint8_t array and back to a string, but I don't receive the same result:

#include <iostream>
#include <string>
#include <sstream> 
#include <vector>

using namespace std;

string ByteArrayToString(const uint8_t *arr, int size) {
    std::ostringstream convert;

    for (int a = 0; a < size; a++) {
        convert << (int)arr[a];
    }

    return convert.str();
}


int main(int argc, char **argv) {
    string str = "10 1d8d532d463c9f8c205d0df7787669a85f93e260 ima-ng sha1:0000000000000000000000000000000000000000 boot_aggregate";

    vector<uint8_t> myVector(str.begin(), str.end());
    uint8_t *tmp = &myVector[0];

    cout << str << endl;
    cout << ByteArrayToString(tmp,  (str.length()/2)) << endl;

    return 0;
}
1

There are 1 answers

0
m.s. On BEST ANSWER

Your cast is causing this, remove it:

for (int a = 0; a < size; a++) {
    convert << arr[a];
}

aside from that, you are only converting half of the string, (length()/2).

live example