Undefined high-order of uint64_t while shifting and masking 32-bit values

前端 未结 1 1330
醉话见心
醉话见心 2020-12-12 06:32

I have some undefined behaviour in a seemingly innocuous function which is parsing a double value from a buffer. I read the double in two halves,

相关标签:
1条回答
  • 2020-12-12 06:49

    If you try to shift a char or unsigned char you're leaving yourself at the mercy of the standard integer promotions. You're better off casting the values yourself, before you try to shift them. You don't have to separate the lower and upper halves if you do so.

    inline double ReadLittleEndianDouble( const unsigned char *buf )
    {
        uint64_t val = ((uint64_t)buf[7] << 56) | ((uint64_t)buf[6] << 48) | ((uint64_t)buf[5] << 40) | ((uint64_t)buf[4] << 32) |
                       ((uint64_t)buf[3] << 24) | ((uint64_t)buf[2] << 16) | ((uint64_t)buf[1] << 8) | (uint64_t)buf[0];
        return *(double*)&val;
    }
    

    All this is necessary only if the CPU is big-endian or if the buffer might not be properly aligned for the CPU architecture, otherwise you can simplify this greatly:

        return *(double*)buf;
    
    0 讨论(0)
提交回复
热议问题