Week 14 Day 2 - Bitfields
Today we encountered the final boss for CSCI 41 - the integer.
Yes - "int x" is a data structure.
On our system, ints are 32 bits, so it is a data structure holding 32 bools in it. For example, if you have a game that has 32 different items in it or less that you can pick up and carry, then you can hold your whole inventory in a single int. (I'd personally use uint32_t to not be surprised if the number of bits changes on a different system - this approach fixes the bits we have at 32.)
To use a bitfield, you need to first name what each of the different bits mean. Since each bit corresponds to a different power of two, each name will be a power of two as well, usually:
const int TELESCOPE = 1;
const int UMBRELLA = 2;
const int KETTLE = 4;
etc.
Then we make our data structure:
uint32_t inv = 0; //Pretty easy, eh?
We can do the usual three operations on a bitfield: insert, search, and delete. All are O(1). In fact, a bitfield can actually do N operations all at once, where N is the size of the bitfield, making its operations O(1/N), kinda, except N doesn't usually scale past 64 or so.
1) Insert. Suppose we want to pick up the umbrella. We would write this code:
inv |= UMBRELLA;
This will add the UMBRELLA (4) to the bitfield if the inventory didn't have it before. If it did have it before, the code does nothing. (No duplicates.)
2) Search. Suppose we want to see if we have the umbrella -
if (inv & UMBRELLA) {
...
}
3) Delete. Suppose we want to get rid of the umbrella:
inv &= ~UMBRELLA;
Done
Other Videos By Bill Kerney
2021-04-21 | Week 15 Day 1 - Shell Scripting, Github |
2021-04-20 | Week 14 Day 1 - Set Theory |
2021-04-19 | Week 15 Day 1 - Multiple Inheritance, Virtual Inheritance, and Smart Pointers |
2021-04-18 | Week 14 - Projecting from World Space to View Space |
2021-04-17 | Week 14 Day 3 - Inheritance |
2021-04-16 | Week 12 Day 3 - Midterm Review |
2021-04-16 | Irish Trad Music Workshop |
2021-04-15 | Week 14 Day 2 - Quake Modding III |
2021-04-15 | Week 14 Day 2 - UNIX Utilities |
2021-04-15 | Week 12 Day 2 - Midterm Review |
2021-04-14 | Week 14 Day 2 - Bitfields |
2021-04-14 | Week 14 Day 1 - Quake Modding |
2021-04-14 | Week 14 Day 1 - Static vs Dynamic Linking |
2021-04-13 | Week 14 Day 1 - Hash Tables and Heaps |
2021-04-13 | Week 12 Day 1 - Cryptography |
2021-04-10 | Week 13 Day 2 - Intro to Modding Quake |
2021-04-10 | Week 13 Day 2 - Enums and Smart Pointers, MMap Part 2 |
2021-04-10 | Week 11 Day 3 - Reproducibility Crisis |
2021-04-09 | Week 13 Day 3 - Guest Lecturer Andrew Bell |
2021-04-09 | Week 11 Day 1 - Dunning Kruger Effect |
2021-04-08 | Week 13 Day 1 - Hash Tables and UNIX Shell Scripting |