Method That Converts Uint8_T to String

Method That Converts Uint8_T to String

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

6

5 Answers

String converter(uint8_t *str){
    return String((char *)str);
}

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.

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>
2
#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,

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;
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Maya Lin-Takahashi
Author

Maya Lin-Takahashi

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.