justinmeiners/lc3-vm

Need help regarding bitwise AND

punpun0 opened this issue · 1 comments

Hello, I need help in this part of the ADD instruction code:

uint16_t r0 = (instr >> 9) & 0x7;

This is my first time using bitwise operations. The tricky part for me is why exactly is & 0x7 used? I understand the intention behind it (getting the register index), but it does not seem intuitive to me and clearly I am missing something. From where does the 0x7 come from? I did the operation by hand and sure enough it does work, but how would I figure this out myself? Excuse me, but I am at loss, everything else before this went smoothly.

Thank you.

See this diagram from the article: https://www.jmeiners.com/lc3-vm/img/add_layout.gif

The destination register occupies 3 bits, starting at the 9th bit. The shift is to get those 3 bits over to the first 3 bits. If you write 0x7 in binary you will notice it has the first 3 bits set. '& 0x7' throws away all the other bits except those 3.

I would prefer if you have article questions to contact me through email. Thanks!