+ 2
Masking of numbers upto unsigned int limit
Hi Let me tell first my understanding of masking. Suppose I have three entities named as (or say identified as) 1,2 and 3. Whether these three entities are present or not (In other words , say they have been created or not) in a file can be easily defined as one boolean for each. But that will take more space. We can go with bitmasking and a single value 8 (2 power 3) can be easily used to identify state of these three entities as state 0 to 7 where 0 means none created and 7 means all three created This works fine. Now, rather than only three entities , I have entities ranging upto unsigned int range. Then how to do bit masking of these large numbers ?
3 Antworten
+ 3
To manipulate bits as flags your options are to use:
1. Bit fields - readable code, but least portable
2. Bitwise operations - fastest, portable, but least readable
3. Bitset library - portable, readable, but slightly slower
You define bit fields in a struct with special syntax. Ported code may break if the CPU has different endian order.
https://en.cppreference.com/w/cpp/language/bit_field
Bitwise operations may appear arcane to those who are unfamiliar.
#define FLAG0 (1<<0)
#define FLAG1 (1<<1)
#define FLAG2 (1<<2)
...
#define FLAG31 (1<<31)
unsigned bitflags = 0;
Set bit: bitflags |= FLAG1;
Reset bit: bitflags &= ~FLAG1;
Flip bit: bitflags ^= FLAG1;
Test bit: (bitflags&FLAG1)!=0
The bitset library object is usually the best option.
https://en.cppreference.com/w/cpp/utility/bitset
+ 1
Maybe you can use long long. If the problem constraints arent enough, try using a string with zeros or ones, or just a vector as you first thought.
I dont think using a single vector will be a problemnin memory.
Now we can think about how to activate one single bit. For that, if the ID is 10 (for example) then create a long long (start by one) and multiply it by 2^(ID-1) (which is the same than moving its bits using << operator and a for loop).
Then, evaluate bitmaskNumber | n (n is the number you just calculated)
Sorry for my weak english, if you need more information ask me again.
+ 1
interesting... you'll end up with quite a large bitset.
There's this discussion:
https://www.gamedev.net/forums/topic/569935-maximum-size-of-a-bitset/4642159/