-1

I get a string which is given as an argument to a function like e.g. 00112233445566778899aabbccddeeff and I need to make an unsigned char array of it which looks like this:

unsigned char array[16]= {0x00 ,0x11 ,0x22 ,0x33 ,0x44 ,0x55 ,0x66 ,0x77 ,0x88 ,0x99 ,0xaa ,0xbb ,0xcc ,0xdd ,0xee ,0xff};

I have no idea how to do it, tried some things with strcpy and thought about hex but this works only with << or >> as I know so I don't think I know how to apply it here. Anyone could help please?

Kala
  • 13
  • 1
  • 1
  • 4

2 Answers2

2

It seems you need to convert each digit received to a nibble and to combine two nibbles into a byte. The conversion from digit to nibble can be done using a look-up or using conditional logic for digits and letters. The combination is a bitwise shift and a bitwise or.

I could write the code but I've somewhat outgrown assignments, not to mention that my version is unlikely to be a viable solution anyway.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
0

You could do this with a combination of istringstream and std::hex. example

#include <iostream>
#include <sstream>


int main() {
    std::string myStr = "1122AA010A";

    std::stringstream ss;
    int n;
    for(int i = 0; i<myStr.length(); ) {
        std::istringstream(myStr.substr(i,2))>>std::hex>>n;
        ss<<(char)n;
        i += 2;
        }

    std::string result = ss.str();

    std::cout<<"\n"<<result<<"\n";
    return 0;
    }
Vincent Ho
  • 106
  • 7