Reputation: 11
From the following link - https://gist.github.com/Romain-P/630f8565cd55b0c52314c47b509b9eb4
Looking at the ADD portion - Why are they subtracting 48 from op1[0],op2[1],op3[0]? I understand the or (|) to combine the ops after left shifting them. Also, why is chch bitwise anded (&) with 0x00ff?
else if (strcmp(token,"add")==0) //----------------- ADD -------------------------------
{
op1 = strtok(NULL,"\n\t\r ");
op2 = strtok(NULL,"\n\t\r ");
op3 = strtok(NULL,"\n\t\r ");
chch = (op1[0]-48)| ((op2[0]-48)<<3)|((op3[0]-48)<<6);
program[counter]=0x7000+((chch)&0x00ff);
counter++;
}
Upvotes: 1
Views: 90
Reputation: 12515
Will turn into an entire answer:
48
== '0'
. This is turning an ASCII number into a range from 0 - 9.
The next part with the shifts is making an assumption. 0 - 9 takes 4 bits to fully encode, but they are only using 3-bits to encode. This will lead to chaos if any of the values are greater than 7.
The "and masking" part is cleaning off extra bits, but since this math should only hold 9 bits as written, that may also be dangerous, as the mask only has room for 8 bits.
All told, the ideas of this code look suspect.
Upvotes: 1
Reputation: 1796
This code, although fairly obtuse, is well commented. When you're getting used to new code, start at the top, and read all of the comments along with the code.
I just did that, and found this useful comment:
48 is ASCII value of '0'
So subtracting 48 from an ASCII '0' - '9' turns it into its numeric equivalent.
Bitwise AND with a constant is known as "masking off" bits. The bits that are 1 in your mask make it through the AND operator, the ones that are 0 are stripped off.
Upvotes: 0