简体   繁体   English

C ++将字符串转换为uint8_t数组并返回

[英]c++ convert string to uint8_t array and back

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: 我正在尝试将字符串转换为uint8_t数组并返回字符串,但是没有收到相同的结果:

#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;
}

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 ). 除此之外,您只转换了一半的字符串( length()/2 )。

live example 现场例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM