5

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

João
  • 449
  • 4
  • 18
user1027620
  • 2,745
  • 5
  • 37
  • 65

5 Answers5

12
String converter(uint8_t *str){
    return String((char *)str);
}
Rudi Strydom
  • 4,417
  • 5
  • 21
  • 30
TRiNE
  • 5,020
  • 1
  • 29
  • 42
3

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

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>
paddy
  • 60,864
  • 6
  • 61
  • 103
  • sstream already includes string and adding the setw flag to the stream every pass isn't needed too – Youka Jul 14 '15 at 22:37
  • 2
    @Youka setw isn't sticky, please see: http://stackoverflow.com/questions/1532640/which-iomanip-manipulators-are-sticky – Snooze Jul 26 '16 at 20:01
1
#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,

Youka
  • 2,646
  • 21
  • 33
1

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;
    }
Mido
  • 1,092
  • 1
  • 9
  • 14