Reputation: 2785
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};
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.
Help is appreciated. Thanks
Upvotes: 5
Views: 85657
Reputation: 5410
String converter(uint8_t *str){
return String((char *)str);
}
Upvotes: 12
Reputation: 1112
You can use a 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;
}
Upvotes: 1
Reputation: 2715
#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,
Upvotes: 1
Reputation: 311126
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.
Upvotes: 3
Reputation: 63481
If the goal is to construct a string of 2-character hex values, you can use a string stream with IO manipulators like this:
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>
Upvotes: 1