-1

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;
}
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
wasp256
  • 5,943
  • 12
  • 72
  • 119

1 Answers1

4

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

m.s.
  • 16,063
  • 7
  • 53
  • 88