Fastest Method to Split a 32 Bit number into Bytes in C++

后端 未结 7 1203
梦谈多话
梦谈多话 2021-01-21 03:15

I am writing a piece of code designed to do some data compression on CLSID structures. I\'m storing them as a compressed stream of 128 bit integers. However, the code in questio

7条回答
  •  被撕碎了的回忆
    2021-01-21 03:58

    Just use a union:

    assert(sizeof (DWORD) == sizeof (BYTE[4]));   // Sanity check
    
    union either {
        DWORD dw;
        struct {
             BYTE b[4];
        } bytes;
    };
    
    either invalidLength;
    invalidLength.dw = (DWORD) invalidClsids.length();
    compressedBytes.push_back(either.bytes.b[0]);
    compressedBytes.push_back(either.bytes.b[1]);
    compressedBytes.push_back(either.bytes.b[2]);
    compressedBytes.push_back(either.bytes.b[3]);
    

    NOTE: Unlike the bit-shifting approach in the original question, this code produces endian-dependent output. This matters only if output from a program running on one computer will be read on a computer with different endianness -- but as there seems to be no measurable speed increase from using this method, you might as well use the more portable bit-shifting approach, just in case.

提交回复
热议问题