C++ 将 uint8_t 转换为字符串的方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31418290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Method that converts uint8_t to string
提问by user1027620
I have this:
我有这个:
uint8_t key[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31};
uint8_t key[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31};
How can I convert it to char or something so that I can read its contents? this is a key i used to encrypt my data using AES.
如何将其转换为 char 或其他内容以便我可以阅读其内容?这是我用来使用 AES 加密数据的密钥。
Help is appreciated. Thanks
帮助表示赞赏。谢谢
回答by TRiNE
String converter(uint8_t *str){
return String((char *)str);
}
回答by Vlad from Moscow
If I have understood correctly you need something like the following
如果我理解正确,您需要类似以下内容
#include <iostream>
#include <string>
#include <numeric>
#include <iterator>
#include <cstdint>
int main()
{
std::uint8_t key[] =
{
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31
};
std::string s;
s.reserve( 100 );
for ( int value : key ) s += std::to_string( value ) + ' ';
std::cout << s << std::endl;
}
The program output is
程序输出是
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
You can remove blanks if you not need them.
如果您不需要它们,您可以删除它们。
Having the string you can process it as you like.
拥有字符串,您可以随意处理它。
回答by Youka
#include <sstream> // std::ostringstream
#include <algorithm> // std::copy
#include <iterator> // std::ostream_iterator
#include <iostream> // std::cout
int main(){
uint8_t key[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31};
std::ostringstream ss;
std::copy(key, key+sizeof(key), std::ostream_iterator<int>(ss, ","));
std::cout << ss.str();
return 0;
}
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29, 30,31,
0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24, 25、26、27、28、29、30、31、
回答by paddy
If the goal is to construct a string of 2-character hex values, you can use a string stream with IO manipulators like this:
如果目标是构造一个由 2 个字符组成的十六进制值字符串,您可以使用带有 IO 操纵器的字符串流,如下所示:
std::string to_hex( uint8_t data[32] )
{
std::ostringstream oss;
oss << std::hex << std::setfill('0');
for( uint8_t val : data )
{
oss << std::setw(2) << (unsigned int)val;
}
return oss.str();
}
This requires the headers:
这需要标题:
<string>
<sstream>
<iomanip>
<string>
<sstream>
<iomanip>
回答by Mido
You can use a stringstream
:
您可以使用stringstream
:
#include <sstream>
void fnPrintArray (uint8_t key[], int length) {
stringstream list;
for (int i=0; i<length; ++i)
{
list << (int)key[i];
}
string key_string = list.str();
cout << key_string << endl;
}