Best way to convert 8 boolean to one byte?

前端 未结 3 1436
感动是毒
感动是毒 2021-01-03 16:52

I want to save 8 boolean to one byte and then save it to a file(this work must be done for a very large data), I\'ve used the following code but I\'m not sure it is the best

3条回答
  •  日久生厌
    2021-01-03 17:18

    Replace the += operator by |=, which is the bit-wise operation (and actually what you want to do here). Use unsigned char for your truth values, if possible.

    Unless you want to hand-unroll your loops and/or use SIMD intrinsics, that would be the most compiler-optimizable solution, I guess.

    there's another trick: structs can have bit offsets, and you can use union on them to misuse them as ints.

    By the way: your code is buggy. You shift first, then write; you use addition, but a signed char, which will definitely go wrong for the 7th and 8th bits (given you erroneously shift too early; if you did that properly, only the 8th bit will cause hazard).

提交回复
热议问题