5

I am following a guide on Gameboy emulation and, in a snippet of code I saw the following:

while(true) 
{ 
  var op = MMU.rb(Z80._r.pc++); // Fetch instruction 
  Z80._map[op]();               // Dispatch 
  Z80._r.pc &= 65535;           // Mask PC to 16 bits 
  Z80._clock.m += Z80._r.m;     // Add time to CPU clock 
  Z80._clock.t += Z80._r.t; 
}

Where pc is a 16-bit program counter register and 65535 in hexadecimal is 0xFFFF , what is the purpose of masking a 16-bit value with 0xFFFF? As far as I know this does nothing? Or is it something to do with the sign bit?

2
  • 2
    You should tag the question with a programming language to get it seen by people familiar with that language. Mar 1, 2015 at 11:25
  • 5
    pc should be 16 bit, but in js, variables are not 16 bit so you need to mask it to 16 bit to emulate a 16 bit variable.
    – mans
    Mar 1, 2015 at 11:25

3 Answers 3

3

I think the important part is that you use JavaScript - it has only one numeric type - floating point. But apparently underlying engine can recognize when it should use integers instead - using bit mask is a strong suggestion that we want to use it as integer since bit operations usually doesn't make sense for floats. It also trims all used pits in this particular variable to last 16 - what guarantee you have that earlier it wasn't using bits older than last 16? If all later operations works on assumption that number is 16-bit then without using mask your assumptions are prone to break.

2

what is the purpose of masking a 16-bit value

None. But there is no 16-bit value - it's just a (floating-point) number in javascript. Only to make it emulate a 16 bit value this number is cut down to 16 bits after the program counter is incremented - it did not overflow from ++ but just did take the value 65536.

That's also what the comment says: // Mask PC to 16 bits.

2

The short answer: it throws out all bits except the 16 lower bits. That way, when run on a 32/64 bit machine, you'll discard all others.

JS uses >16 bits and to ensure you're working with 16 bits only you discard the rest by AND-ing with 0xFFFF (or 65535). In this particular example the program-counter, which is 16 bits on a gameboy (apparently :P ), is 'wrapped around' to 0 when the value reaches 65536. An if (Z80._r.pc > 65535) Z80._r.pc = 0 would do the same but would probably perform worse. This kind of "trick" is used very often in bit manipulation code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.