Tell me, please, how to convert a direct code to decimal?

The direct code lies in the vector:

std::vector<uint8_t> code; 

Vector content: 0x90 0xa8 0x02 . In this case, code[0] is the decimal part, and in code[2] and code[1] intact. And the most significant bit in code[2] denotes the sign of a number.

I implemented it like this:

  // calculate int8_t pm = 1; if (result[2] & 1<<7){ pm=-1; result[2] ^= 1<<7; } y = (result[2]*256 + result[1] + result[0]/256.0) * pm; 

The result is correct. But somehow long and, it seems to me, ineffective.

    1 answer 1

    Of course, you can make fun and do this:

     double dres(const vector<unsigned char>&result) { struct Data { unsigned long i: 23; int sign : 1; }; Data *d = (Data*)&result[0]; return double(d->i)/256 *(d->sign ? -1 : 1); } 

    Well, you understand the principle?

    I really dislike you for changing result[2] :

     result[2] ^= 1<<7; 
    • 2
      For little-endian (for example, x-86) is correct, and for big-endian zero and second bytes will have to be swapped. - avp
    • @Harry, I understand your code. I'm still completely new to C / C ++, so it’s not obvious. But I'll figure it out. - ddipp