LoginLogin

How do I remove certain bits from a binary number

Root / Programming Questions / [.]

Yellow01Created:
I know that NOT inverts the whole number, AND compares pairs of bits and outputs 1 if they are the same, OR combines numbers, and XOR only works if the bits aren't the same. The program I'm trying to make is like a paint program for 2BPP graphics, and in order to overwrite numbers I'll have to get rid of a certain pair of bits. Unfortunately, I have no idea on how to go about doing that. My intention: variables: PIXELS (group of 4 2bpp pixels) SUBPIXEL (which 2bpp pixel to select, MOD 4) COLOR (up to &B11) replace a set of 2 bits with COLOR depending on SUBPIXEL example: PIXELS = &B11000110 SUBPIXEL = 0 COLOR = &B01 &B*11*000110 V replace bits with 00 &B*00*000110 V replace bits with COLOR &B*01*000110

You just have to AND it with a number where 1 marks the bits you want to keep, and 0 marks the bits you don't want to keep. So, for your example, you would AND it with &B00111111 to clear the top two bits, and then OR it with &B01000000.

The problem is, i'm not always modifying the same 2 bits. the example i showed was when SUBPIXEL = 0. I'm not sure how to make it work with other values.

You can use << and >> to shift a number by a given number of bits left or right. So, for example, let's start with &B11. We can shift it like this:
&B11 << 6 becomes &B11000000
&B11 << 4 becomes &B00110000
&B11 << 2 becomes &B00001100
&B11 << 0 becomes &B00000011
These correspond to SUBPIXEL = 0 through 3, so we can calculate the amount we need to shift to the left as 6 - 2*SUBPIXEL. If we invert these numbers with NOT, we can then AND it with PIXELS to clear the bits for that SUBPIXEL. Then, we just need to shift COLORS by the same amount, and OR it with PIXELS. So, the code ends up looking like this:
SHIFT = 6 - 2*SUBPIXEL
PIXELS = PIXELS AND NOT (&B11 << SHIFT)
PIXELS = PIXELS OR (COLOR << SHIFT)

Yep, that's it. Just tried it out and it works! Thanks a bunch!