簡體   English   中英

C ++將字符串轉換為uint8_t數組並返回

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

我正在嘗試將字符串轉換為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;
}

您的演員表導致了此問題,請將其刪除:

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

除此之外,您只轉換了一半的字符串( length()/2 )。

現場例子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM