C++ bitfield packing with bools

前端 未结 6 1293
北恋
北恋 2020-12-05 04:19

I\'ve just done a test with bitfields, and the results are surprising me.

class test1 {
public:
    bool test_a:1;
    bool test_b:1;
    bool test_c:1;
            


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-05 05:26

    As a general observation, a signed int of 1 bit doesn't make a lot of sense. Sure, you can probably figure out how to store 0 in it, but then the trouble starts.

    One bit must be the sign-bit, even in two's complement, but you only have one bit to play with. So, if you allocate that as the sign-bit, you have no bits left for the actual value. It's true as Steve Jessop points out in a comment that you could probably represent -1 if using two's complement, but I still think that an "integer" datatype that can only represent 0 and -1 is a rather weird thing.

    To me, this datatypes makes no (or, given Steve's comment, little) sense.

    Use unsigned int small : 1; to make it unsigned, then you can store the values 0 and 1 in a non-ambiguous manner.

提交回复
热议问题