Bitwise operations will help me serialize some bools?

I am not used to binaries and I am trying to figure this out. I managed to save integers and unsigned char, and read them without any problems. Now, when I try to save some booleans, I see that each of my bools occupies exactly 1 octet in my file, which seems logical, since a single bool is stored in char data (correct me if I am "wrong!).

But since I will have 3 or 4 bools for serialization, I suppose it is a waste to store them like this: 00000001 00000001 00000000, for example, when I could have 00000110. I think to get this I have to use the bitwise operation but I'm not very good with them ... so can someone tell me:

  • How to save up to 8 bools in one octet using bitwise manipulations?
  • How to transfer correct values ​​(up to 8 bools) from one octet using bitwise manipulation?
  • (And, a bonus question, can anyone recommend a simple, non-mathematical-oriented mind like mine, a bit of manipulation tutorial, if that exists? All that I found, I understood, but could not put into practice .. .)

I use C ++, but I assume that most C-syntax languages ​​will use the same kind of work.

+3
source share
6 answers

To store bools in bytes:

bool flag; // value to store
unsigned char b = 0; // all false
int position; // ranges from 0..7
b = b | (flag << position);

To read it:

flag = (b & (1 << position));
+2
source

std:: bitset, (bools), . .

int main() {
  std::bitset<8> s;
  s[1] = s[2] = true;  // 0b_0000_0110
  cout << s.to_ulong() << '\n';
}
+2

/ :

  • 3 var:
    var |= (1 << 3)
  • n var:
    var |= (1 << n)
  • n var:
    var &= ~(1 << n)
  • n var: (!! , 0 1)
    !!(var & (1 << n))
+1

:

  • , false, 00000000, true i.e: 00001000,01010101
  • 00000000 = 0 (), 00000001 = 2 ^ 0, 00000010 = 2 ^ 1, 00000100 = 2 ^ 2,...., 10000000 = 2 ^ 7
  • (& &, ||) (&, |) , :

    00000000 && 00000000 = false,

    01010101 && 10101010 = true

    00001100 || 00000000 = true,

    00000000 || 00000000 = false

    ( ):

    00000000 00000000 = 00000000 = false

    00001111 11110000 = 00000000 = false

    01010101 10101001 = 00000001 = true

    00001111 | 11110000 = 11111111 = true

    00001100 | 00000011 = 00001111 = true


, :

  • 1, | , 1 ceros .

: , A 1: A | 00000001

  • 0, , 0 , - .

: , A 0, : A & 01111111

  • , , , 1 , - .

For example: we want to see the value of the third bit of octet A, we do: A & 00000100, if A was XXXXX1XX we get 00000100 = true, and if A was XXXXX0XX we get 00000000 = false;

+1
source

You can always serialize beatpods. Sort of:

struct bools 
{
    bool a:1;
    bool b:1;
    bool c:1;
    bool d:1;
};

has size 1

0
source

Source: https://habr.com/ru/post/1789181/


All Articles