Is there a more efficient way of expanding a char to an uint64_t?

前端 未结 8 696
星月不相逢
星月不相逢 2021-01-18 06:32

I want to inflate an unsigned char to an uint64_t by repeating each bit 8 times. E.g.

char -> uint64_t
0x00 -> 0x00
0x01 ->         


        
8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-18 07:01

    If you're willing to spend 256 * 8 = 2kB of memory on this (i.e. become less efficient in terms of memory, but more efficient in terms of CPU cycles needed), the most efficient way would be to pre-compute a lookup table:

    static uint64_t inflate(unsigned char a) {
        static const uint64_t charToUInt64[256] = {
            0x0000000000000000, 0x00000000000000FF, 0x000000000000FF00, 0x000000000000FFFF,
            // ...
        };
    
        return charToUInt64[a];
    }
    

提交回复
热议问题