Best way to convert 8 boolean to one byte?

前端 未结 3 1358
感动是毒
感动是毒 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:15

    Regarding

    can anyone give me a better code(more speed)

    you should measure. Most of the impact on the speed of serializing to file is i/o speed. What you do with the bits will likely have an unmeasurably small impact, but if it has any impact then that is likely mostly influenced by your original representation of the sequence of booleans.


    Now regarding the given code

    int bits[]={1,0,0,0,0,1,1,1};
    char a='\0';
    for (int i=0;i<8;i++){
    a=a<<1;
    a+=bits[i]
    }
    //and then save "a"
    
    • Use unsigned char as byte type, just on principle.
    • Use bitlevel OR, the | operator, again just on principle.
    • Use prefix ++, yes, also that just on principle.

    The “on principle” for the first point is because in practice your code will not run on any machine with sign-and-magnitude or one's complement representation of signed integers, where char is signed. But I think it's generally a good idea to express in the code exactly what one intends doing, instead of rewriting it as something slightly different. And the intention here is to deal with bits, an unsigned byte.

    The “on principle” for the bitlevel OR is because for this particular case there's no practical difference between bitlevel OR and addition. But in general it's a good idea to write in code what one means to express. And then it's no good to write a bitlevel OR as an addition: it might even trip you up, bite you in the a**, in some other context.

    The “on principle” for the prefix ++ is because in practice the compiler will optimize prefix and postfix ++ for a basic type, when the expression result isn't used, to the very same machine code. But again it's generally better to write what one intends to express. Asking for an original value (the postfix ++) is just misleading a reader of the code when you're not ever using that original value – and as with the bitlevel OR expressed as addition, the pure increment expressed as postfix ++ might trip you up, bite you in the a**, in some other context, e.g. with iterators.


    The general approach of explicitly coding up shifting and ORing appears to me to be fine because std::bitset does not support initialization from a sequence of booleans (only initialization from a text string), so it doesn't save you any work. But generally it's a good idea to check the standard library, whether it supports whatever one wants to do. It might even happen that someone else chimes in here with some standard library based approach that I didn't think of! ;-)

提交回复
热议问题