Is a bit field any more efficient (computationally) than masking bits and extracting the data by hand?

后端 未结 7 1652
庸人自扰
庸人自扰 2021-02-08 10:16

I have a numerous small pieces of data that I want to be able to shove into one larger data type. Let\'s say that, hypothetically, this is a date and time. The obvious method is

7条回答
  •  遥遥无期
    2021-02-08 11:06

    Those will probably compile the the same machine code, but if it really matters, benchmark it. Or, better yet, just use the bitfield because it's easier!

    Quickly testing gcc yields:

    shrq    $6, %rdi             ; using bit field
    movl    %edi, %eax
    andl    $31, %eax
    

    vs.

    andl    $130023424, %edi     ; by-hand
    shrl    $21, %edi
    movl    %edi, %eax
    

    This is a little-endian machine, so the numbers are different, but the three instructions are nearly same.

提交回复
热议问题