Math |
|
To
binary invert (Complement) a variable, use the correct operator... (~) Is the proper operator to complement a bit, byte etc. (-) Treats a variable like a signed value, not straight binary. (!) Treats a variable like a Boolean, 0=false / not 0=true. |
INT1
bitv; CHAR temp; //--------------------------------------------------- bitv = ~bitv; //proper way to invert a bit temp = ~temp; //proper way to invert a byte, etc //--------------------------------------------------- bitv != bitv; //a bunch of code that does nothing bitv = !bitv; //this actually will invert bitv bitv = -bitv; //a bunch of code to invert a bit! //--------------------------------------------------- temp = temp^255; //inverts temp, wastes 1 opcode temp = -temp; //gets the 2's complement (signed) //1 >> (-1) >> 255 temp = !temp; //if temp was 0, temp is now 0 //if temp was >0, temp is now 1 temp != temp; //a bunch of code that does nothing |
Both of these will increment the variable tempxx by one. (The longer one should be fixed after PICC-3.23x?). Note that these rules apply to decrementing operations as well! |
CHAR
temp; temp++; //This will generate the code: // INCF (temp),f ++temp; //This is equivalent to temp++; temp=temp+1; //This will generate the code: // MOVLW 1 // ADDWF (temp),f |
Prefix and Postfix incrementing. the position on "++" determines whether tempy is incremented before or after it is used in the wider equation. Note that these rules apply to decrementing operations as well! |
CHAR
tempx; CHAR tempy; tempx=0; tempy=5; tempx= ++tempy + 6; //now tempx=12 and tempy=6 tempx=0; tempy=5; tempx= ++tempy + 6; //now tempx=11 and tempy=6 |
Variables in an equation need to be of the same type else results will be unpredictable. You can force a variable of one type to be treated temporarily like another... Otherwise, the result will be the size of the smallest operand. |
CHAR
operand8=150; INT16 operand16; //operand 16 will be (300 mod 256) or 44 operand16=operand8 * 2; //operand 16 will be 300 operand16=(INT16) operand8 * 2; |
Adding a constant to a variable also requires the correct order of the operators... The first two examples generate the same size of code in PICC-3.233 (unlike the increment example). |
CHAR
temp=5; temp=temp+5; //temp now equals 10 temp+=5; //temp now equals 15 temp=+5; //temp now equals 5 (positive 5) |
Any questions or comments?
This page last updated on
May 04, 2009