-1

I have a method which gets a string of consecutive bytes and i need an array of bytes out of it:

void  GetByteArray(string paddedResistance)
{
   unsigned char cmd[4]={0x00,0x00,0x00,0x00};


   list<string> resistanceBytesAsString;


   for (int i = 0; i < paddedResistance.size(); i+=2)
   {
       resistanceBytesAsString.push_back(paddedResistance.substr(i, 2));

   }
}

This is the input value : "00000100"

and i will split it and add it to the list as four separate strings:

00 00 01 00

I need to convert each of them in order to be able to populate the cmd unsigned char array but i can't figure out how to do it.

In C# i would use

Convert.ToByte(myString, 16);

to populate a byte array.

Olaru Mircea
  • 2,570
  • 26
  • 49
  • So, you want the string `"00000100"` to be converted to the binary value `{00, 00, 01, 00}`? I'm pretty sure that `Convert.ToByte` doesn't do THAT, but converts to `{ '0', '0', '0', '0', '0', '1', '0', '0', '0' }`, which is quite different. – Mats Petersson Jul 21 '15 at 07:50
  • @MatsPetersson I am pretty sure this works in c# : Convert.ToByte("FF", 16)) and i will have my byte value as expected. – Olaru Mircea Jul 21 '15 at 07:54
  • Ah, I see what it does. The answer to your question is more complex than the answers given below however. [And I expect on an x86 machine (and any other little endian machine), the output would be `{0x00, 0x01, 0x00, 0x00}`]. – Mats Petersson Jul 21 '15 at 07:57
  • 2
    The duplicate question IS NOT the answer here... It's missing a "Convert from hex". – Mats Petersson Jul 21 '15 at 07:57
  • @MatsPetersson indeed, i am sorry i omitted that. That cmd that should populated is initialized with 0x00 values as a hint, for some reason i thought is enough...And i also used the c# conversion from hexadecimal. – Olaru Mircea Jul 21 '15 at 08:00
  • I have reopened the question. I don't fancy coming up with the approximately three or four lines of C++ code right now (gotta go to work, earn some beer-tokens [although most will probably go on something other than beer]) – Mats Petersson Jul 21 '15 at 08:24

1 Answers1

1

Consider using something like this:

std::vector<std::string> resistanceBytesAsString{"00","01","10","11"};

std::vector<unsigned char> bytes(resistanceBytesAsString.size());
std::transform(
    resistanceBytesAsString.begin(), 
    resistanceBytesAsString.end(),
    bytes.begin(),
    [](const std::string& str) {
        // Convert the string of length 2 to byte.
        // You could also use a stringstream with hex option.
        unsigned char byte = (str[0] - '0') << 1 | (str[1] - '0');
        return byte;
});

Live working example

Beta Carotin
  • 1,659
  • 1
  • 10
  • 27