简体   繁体   English

将 uint8_t 数组转换为 C++ 中的字符串

[英]Convert array of uint8_t to string in C++

I have an array of type uint8_t.我有一个 uint8_t 类型的数组。 I want to create a string that concatenates each element of the array.我想创建一个字符串来连接数组的每个元素。 Here is my attempt using an ostringstream, but the string seems to be empty afterward.这是我使用 ostringstream 的尝试,但之后字符串似乎为空。

std::string key = "";
std::ostringstream convert;
for (int a = 0; a < key_size_; a++) {                                               
  convert << key_arr[a]
  key.append(convert.str());
}

cout << key << endl;

Try this:尝试这个:

std::ostringstream convert;
for (int a = 0; a < key_size_; a++) {
    convert << (int)key[a];
}

std::string key_string = convert.str();

std::cout << key_string << std::endl;

The ostringstream class is like a string builder. ostringstream类就像一个字符串生成器。 You can append values to it, and when you're done you can call it's .str() method to get a std::string that contains everything you put into it.你可以给它.str()完成后你可以调用它的.str()方法来获取一个std::string ,其中包含你放入的所有内容。

You need to cast the uint8_t values to int before you add them to the ostringstream because if you don't it will treat them as chars.在将uint8_t值添加到ostringstream之前,您需要将它们转换为int ,因为如果不这样做,它会将它们视为字符。 On the other hand, if they do represent chars, you need to remove the (int) cast to see the actual characters.另一方面,如果它们确实代表字符,则需要删除(int)强制转换以查看实际字符。


EDIT: If your array contains 0x1F 0x1F 0x1F and you want your string to be 1F1F1F, you can use std::uppercase and std::hex manipulators, like this:编辑:如果您的数组包含 0x1F 0x1F 0x1F 并且您希望您的字符串为 1F1F1F,则可以使用std::uppercasestd::hex操作符,如下所示:

std::ostringstream convert;
for (int a = 0; a < key_size_; a++) {
    convert << std::uppercase << std::hex << (int)key[a];
}

If you want to go back to decimal and lowercase, you need to use std::nouppercase and std::dec .如果你想回到十进制和小写,你需要使用std::nouppercasestd::dec

This works for me: 这对我有用:

#include <string>
#include <iostream>

int main()
{

    uint8_t arr[] = {'h', 'i'};

    std::string s;

    s.assign(arr, arr + sizeof(arr));

    std::cout << s << '\n';
}

You can also use the string's constructor: 您还可以使用字符串的构造函数:

std::string s(arr, arr + sizeof(arr));

Probably the easiest way is可能最简单的方法是

uint16_t arr[];
// ...
std::string str = reinterpret_cast<char *>(arr); 

or C-style:或 C 风格:

std::string str = (char *) arr;

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

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