Kategorien
C

Bit-orientierte Operationen in C

Bitwise AND

0 & 0 == 0

0 & 1 == 0

1 & 0 == 0

1 & 1 == 1

Bsp
int a = 0x005A; // a = 10 +  16*5 = 90, in binary: 0000 0000 0101 1010, 2 + 8 + 16 + 64 = 90
int b = 0x00F0; // b = 0 + 16*15 = 240, in binary: 0000 0000 1111 0000, 16 + 32 +64 + 128 = 240
int x = a & b; //                                  0000 0000 0101 0000, 16 + 64 = 80

Bitwise OR

0 | 0 == 0

0 | 1 == 1

1 | 0 == 1

1 | 1 == 1

Bsp
int a = 0x005A; // a = 10 +  16*5 = 90, in binary: 0000 0000 0101 1010, 2 + 8 + 16 + 64 = 90
int b = 0x00F0; // b = 0 + 16*15 = 240, in binary: 0000 0000 1111 0000, 16 + 32 +64 + 128 = 240
int x = a | b; //                                  0000 0000 1111 1010, 2 + 8 + 16 + 32 + 64 + 128 = 250

Bitwise XOR

0 ^ 0 == 0

0 ^ 1 == 1

1 ^ 0 == 1

1 ^ 1 == 0

Bsp
int a = 0x005A; // a = 10 +  16*5 = 90, in binary: 0000 0000 0101 1010, 2 + 8 + 16 + 64 = 90
int b = 0x00F0; // b = 0 + 16*15 = 240, in binary: 0000 0000 1111 0000, 16 + 32 +64 + 128 = 240
int x = a ^ b; //                                  0000 0000 1010 1010, 2 + 8 + 32 + 128 = 170

Bitwise NOT

~0 == 1

~1 == 0

Bsp
int a = 0x005A; // a = 10 +  16*5 = 90, in binary: 0000 0000 0101 1010, 2 + 8 + 16 + 64 = 90
int x = ~a; //                                      1111 1111 1010 0101, irgendwas großes :)

Bitwise Shift

1<<0 == 1

1<<1 == 2

1<<2 == 4

1<<3 == 8

Bsp
int a = 0x005A; // a = 10 +  16*5 = 90, in binary: 0000 0000 0101 1010, 2 + 8 + 16 + 64 = 90
int x = a<<4; //                                   0000 0101 1010 0000
int y = a>>3; //                                   0000 0000 0000 1011