0
Can someone explain what Bit Masking is used for and how?
I read about the bit masking in bitwise operations but i still don't quite understand it.
1 Odpowiedź
+ 5
Two places I've used bit masking are accessing device hardware registers and generating machine code in compilers. Back in the days of memory being tight, it was used a lot more than now days.
The concept is storing multiple data values in a single addressable memory location. With the memory existing today, it doesn't make sense to bother because of the cost of putting the data in or taking it out.
Say you have two variables: 'a' with a range of 0..3 and 'b' with a range of 0..64. They could fit in 8 bits (2 for 'a' & 6 for 'b'.) To put 'b' into the data, you could code:
data = (data & 0xc0) | b;
"(data & 0xc0)" tosses the old 'b' value and saves the 'a' value. The "| b" adds the new 'b' value. To retrive 'b' value, you could code:
b = data & 0x3f;