6 years, 4 months ago.

Converting a vector uint8_t so I can work with it.

Hello,

So I have been struggling for two days now but it seems there is no way to do this. I hope someone can proof me different. I have I following code:

std::vector<uint8_t> response;

if ((ret = dot->recv(response)) != mDot::MDOT_OK) { logError("failed to recv: [%d][%s]", ret, mDot::getReturnCodeString(ret).c_str()); } else {

logInfo("recv data: %s", response);

int cmd, value;

}

So I receive a message on my device which is now 1,20 (response) But it can also be like 1,20,3,2,1,2 The only thing I want is to convert this vector to a char so I can use sscanf to read out the data. Seems impossible for me.

I'm normaly a web developer, so I don't do alot with bits and bytes since it's not needed...

I hope someone can help me!

1 Answer

6 years, 4 months ago.

It's not the most efficient solution but you can convert the vector into a char array at which point you can use all of the standard c functions on it. You can access vectors in the same way as you do arrays so the code is fairly straight forward:

#define maxResponseLength 20
char dataIn[maxResponseLength+1]; // allow space for the null on the end

int responseLen = response.size();            // check the length
if (responseLen > maxResponseLength)
  responseLen  = maxResponseLength;

for (int i = 0; i<responseLen ; i++) {
  dataIn[i] = response[i];
}

dataIn[responseLen] = 0; // add the termination

// dataIn now contains the data from response but in a char array with a null terminator, the standard c string format.

This isn't going to be the fastest or most memory efficient solution but it is simple.

Also for future reference if you do

<<code>>
your code
<</code>>

then the formatting doesn't get messed up.

Accepted Answer

Hello Andy,

Thank you for responding. So I implemented your code, but this is the result.

        char dataIn[20+1]; // allow space for the null on the end
        int responseLen = response.size();            // check the length
        if (responseLen > 20)
          responseLen  = 20;
         
        for (int i = 0; i<responseLen ; i++) {
          dataIn[i] = response[i];
        }
        dataIn[responseLen] = 0; // add the termination

        int cmd, value;
        sscanf(dataIn,"%d,%d",cmd,value);
        logInfo("cmd: %d, value: %d", cmd,value); 

Result in console is: cmd: 536871392, value: 536871452 Should be: cmd: 1, value: 20

posted by Roel Gellings 19 Dec 2017

Hey Andy,

I got it fixed, forgot the & inside the sscanf function:

sscanf(dataIn,"%d,%d",&cmd,&value);

Thankyou!

posted by Roel Gellings 19 Dec 2017