When is it worthwhile to use bit fields?

前端 未结 11 593
伪装坚强ぢ
伪装坚强ぢ 2020-12-01 09:10

Is it worthwhile using C\'s bit-field implementation? If so, when is it ever used?

I was looking through some emulator code and it looks like the registers for the c

11条回答
  •  Happy的楠姐
    2020-12-01 09:41

    One use for bitfields which hasn't yet been mentioned is that unsigned bitfields provide arithmetic modulo a power-of-two "for free". For example, given:

    struct { unsigned x:10; } foo;
    

    arithmetic on foo.x will be performed modulo 210 = 1024.

    (The same can be achieved directly by using bitwise & operations, of course - but sometimes it might lead to clearer code to have the compiler do it for you).

提交回复
热议问题