Question

I am writing a CHIP8 emulator. I wrote everything so far, except for the opcode DXYN, I looked for some explaination for it, and I found a question in SO, with a code as answer for it. While reading the code, I got stuck on this piece of code which in C says if((data & (0x80 >> x)) != 0) what does the (data & (0x80 >> x)) do exactly?

Was it helpful?

Solution 2

If we split it up, we have

0x80 >> x

which shifts the value 128 (0x80) right by x bits.

The next part uses the previous result as a mask for data, to see if the specific bit it set in data.

Then the whole is checked against zero to see if the bit is set or not.

OTHER TIPS

The if statement checks if bit #x is set in a byte, counting 0 as the highest bit.

Bit#  01234567
      01001010   (0x4A has bit 1, 4 and 6 set)

(data & (0x80 >> x)) returns 0x40 for x=1
                             0x08 for x=4
                             0x02 for x=6
                             0x00 for all other values.

if((data & (0x80 >> x)) != 0) is in other words true for x=1, x=4 and x=6

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top