Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method that converts uint8_t to string

Tags:

c++

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

like image 264
user1027620 Avatar asked Jul 14 '15 22:07

user1027620


4 Answers

String converter(uint8_t *str){
    return String((char *)str);
}
like image 186
TRiNE Avatar answered Oct 23 '22 08:10

TRiNE


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.

like image 30
Vlad from Moscow Avatar answered Oct 23 '22 07:10

Vlad from Moscow


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

like image 1
Youka Avatar answered Oct 23 '22 06:10

Youka


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;
    }
like image 1
Mido Avatar answered Oct 23 '22 07:10

Mido