BigEd wrote:
glad you got it! I don't quite understand it myself. Is pc a signed type? I think you have to work through the implicit conversions from one type to another. An explicit cast might be the answer, but it's best to know exactly why it is needed before adding a cast.
Cheers
Ed
"pc" must be an unsigned int because there's no negative values for the memory directions.
i'll explain it step by step:
1. pc += 2;
we increment in 2 bytes de pc, so it points to the next instruction after the BNE before the branch is added
2. if(zflag == 0)
if Z flag is not set then...
3. pc--;
since we'll have to branch we need to decrement the pc, because the byte after the BNE instruction (wich is the signed byte that gives the displacement) is relative to this byte
4. if(memory[pc] > 0x7f) pc -= (~memory[pc] & 0x00ff);
if the byte that gives the displacement is major than $7F then the higher bit is 1, so it's a negative branch. to calculate the displacement, what we do is to calculate the 1's compliment of the value given by the byte. after this last operation, our C++ will give as result a 2 bytes integer. since we need to discard the higher byte of that number, we apply yo it a logical AND using $00FF, so after this operation the higher byte of the integer is 0. and then we finally substract that value to the pc.
in e.g.: supose we have the value F5, which is a 1 byte integer. after apply the ~ operation, C++ will return FF0A, wich is a 2 bytes integer. note that 0A is the 1's compliment of F5, and that's the value we need to substract from the pc. then we use the logical AND with 00FF, and afther that FF0A turns to 0A, and there you go ;D
5. else pc += (memory[pc] & 0x00ff);
if it's a positive branch we simply add the byte next to BNE to the pc. the operation " & 0x00ff" it's not needed, but i just recently figured out that XD
is it clear now?? any doubts feel free to ask!