gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

Coding > Bit setting

#3779 - Maverick - Sat Mar 08, 2003 7:43 pm

It is easy to set a bit in an address

ie *(u16 *)VRAM = 0x50;

for example.

But how would you go about changing that back to 0 without touching the other bits.

ie 0010010
to 0010000
?

#3784 - DekuTree64 - Sat Mar 08, 2003 8:56 pm

Do like var = var & ~bit. The ~ (called not) operator changes all 1 bits to 0's, and all 0's to 1's. So then all bits except the ones that you specify before reversing it will stay set, and all the ones you do specify will be cleared. You can also use ^ (xor) to toggle bits on and off (handy for flashing effects and stuff)

#3787 - Maverick - Sat Mar 08, 2003 10:00 pm

Sorry, i dont understand, ive used ~ before, it just basically turns 100 into 155.

255 - x = y

255 - 100 = 155

but ive never used ^

How would this be used?

how could i use ~?

eg

if x = 100
~x = 155

if x = 100
^x = ?

#3788 - Lord Graga - Sat Mar 08, 2003 10:02 pm

Look at this code:

if(REG_DISPCNT & BACKBUFFER)
{
//Switch to front buffer hidden
REG_DISPCNT &= ~BACKBUFFER;
VideoBuffer = BackBuffer;
}
//Otherwise front buffer is hidden
else
{
//Switch to back buffer hidden
REG_DISPCNT |= BACKBUFFER;
VideoBuffer = FrontBuffer;
}

#4102 - fatgraham - Wed Mar 19, 2003 12:49 am

and, where bit AND bit
10101011
& 01110011
= 00100011

or, where bit OR bit
10101011
| 01110011
= 11111011

xor, where bit OR bit, but not both
10101011
^ 01110011
= 11011000

not, where NOT a bit
~ 10101011
= 01010100

now, obviously the &= applies AND to the variable
so, if we AND, NOT &=~

10101011 &
~01110011 (which is 10001100)
= 10001000

which is what you want to do, if you want to remove some bits

0xff & (0x0f) = 0x0f // keep 0x0f
0xff & ~(0x0f) = 0xf0 // keep the opposite of 0x0f




Ive always found thinking of everything in terms of bits, and memory (a variable isnt a number, its some memory!) has helped me understand everything, ever
_________________
http://www.fatgrah.am/