Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Masking a 16-bit value with 0xFFFF

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?

like image 616
Nubcake Avatar asked Mar 01 '15 11:03

Nubcake


1 Answers

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.

like image 135
Mateusz Kubuszok Avatar answered Sep 18 '22 16:09

Mateusz Kubuszok