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

后端 未结 7 1799
庸人自扰
庸人自扰 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:47

    Depends. If you use bit fields, then you let the compiler worry about how to store the data (bitfields are pretty much completely implementation-defined), which means that:

    • It might use more space than necessary, and
    • Accessing each member will be done efficiently.

    The compiler will typically organize the layout of the struct so that the second assumption holds, at the cost of total size of the struct.

    The compiler will probably insert padding between each member, to ease access to each field.

    On the other hand, if you just store everything in a single unsigned long (or an array of chars), then it's up to you to implement efficient access, but you have a guarantee of the layout. It will take up a fixed size, and there will be no padding. And that means that copying the value around may get less expensive. And it'll be more portable (assuming you use a fixed-size int type instead of just unsigned int).

提交回复
热议问题