溫馨提示×

C++ byte數組怎樣轉換為字符串

c++
小樊
385
2024-07-13 17:34:25
欄目: 編程語言

在C++中,可以使用以下方法將字節數組轉換為字符串:

  1. 使用循環遍歷字節數組,將每個字節轉換為字符,然后拼接到字符串中。例如:
#include <iostream>
#include <string>

int main() {
    unsigned char byteArray[] = {0x48, 0x65, 0x6c, 0x6c, 0x6f};
    std::string str;

    for (int i = 0; i < sizeof(byteArray); i++) {
        str += byteArray[i];
    }

    std::cout << str << std::endl;

    return 0;
}
  1. 使用C++標準庫中的 std::string 構造函數,將字節數組作為參數傳入。例如:
#include <iostream>
#include <string>

int main() {
    unsigned char byteArray[] = {0x48, 0x65, 0x6c, 0x6c, 0x6f};
    std::string str(reinterpret_cast<char*>(byteArray), sizeof(byteArray));

    std::cout << str << std::endl;

    return 0;
}

這兩種方法都可以將字節數組轉換為字符串,可以根據具體需求選擇合適的方法。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女