Intermediate C++ Game Programming Tutorial 23
From Chilipedia
Bit twiddling is a lot of bullshit that is usually avoided when possible because it leads to ass code. Still, it is necessary in various situations, so you gotta learn this shit, and now is as good a time as any I guess.
Topics Covered
- Bitwise AND (&), OR (|), and shift left/right (>> and <<)
- Unary bitwise NOT/complement (~) and bitwise XOR (^)
- Masking with & and combining with |
- Packing and unpacking smaller data in larger types
- Bit flags
- Bitwise arithmetic optimizations
Video Timestamp Index
[Expand]
- Introducing
std::string ToBin(unsigned int n, int min_digits=0);
to convert integers to their binary representation 0:15 - Bitwise operators AND (
&
), OR (|
) 1:50
- Shifting operations left (
<<
), right (>>
) 5:10
- Packing and unpacking data 7:07
- Example use case: The
Color
class in the Framework 12:20
- Packing flag values into a single integer parameter 14:29
- Advanced Bitwise operators NOT (
~
), XOR (^
) 16:48- Bitwise NOT (
~a
): unary operation that flips all the bits ofa
- - Use case: with off an option:
options &= ~option1;
- Bitwise XOR (
^
): binary operation sets each bit position to 1 only if the bits at that position of the two operands are different
- Bitwise NOT (
Homework
- Figure out how the binary string formatter routine works
- Figure out why
x % 16
compiles tox & 0xF
The solution for the problems will not have its own video. Feel free to come on the discord and compare your answers with others, or to ask specific questions if you are having trouble understanding.