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

后端 未结 7 1648
庸人自扰
庸人自扰 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 10:54

    The compiler can sometimes combine the access to the bitfields in a non intuitive matter. I once disassembled the code generated (gcc 3.4.6 for sparc) when accessing 1 bit entries that where used in a conditionnal expressions. The compiler fused the access to the bits and made the comparison with integers. I will try to reproduce the idea (not at work and can not access the source code that was involved):

    struct bits {
      int b1:1;
      int b2:1;
      int b3:1;
      ...
    } x;
    
    if(x.b1 && x.b2 && !x.b3)
    ...
    if(x.b2 && !x.b2 && x.b3)
    

    was compiled to something equivalent to (I know the bitorder in my example is the opposite but it is only for the sake of simplification of the example).

    temp = (x & 7);
    if( temp == 6)
    ...
    if( temp == 5)
    

    There's also another point to consider if one wants to use bitfields (they are often more readable than bit-kungfu), if you have some bits to spare, it can be useful to reserve whole bytes for certain fields, thus simplifying access by the processor. An 8 bits field that is aligned can be loaded with a move byte command and doesn't need the masking step.

提交回复
热议问题