Two's compliment in PBasic?
lindseydallas
Posts: 14
Hello,
Is there a command in PBasic to do a two's compliment on a binary number? Has anyone else had to do this?
Two's compliment is when you take a binary number and switch the 0s to 1s and the 1s to 0s and then add one.
For example:
Take
10101010 then do the switch
01010101 then add one
01010110 gives the two's compliment
Any ideas?
Thanks!
Is there a command in PBasic to do a two's compliment on a binary number? Has anyone else had to do this?
Two's compliment is when you take a binary number and switch the 0s to 1s and the 1s to 0s and then add one.
For example:
Take
10101010 then do the switch
01010101 then add one
01010110 gives the two's compliment
Any ideas?
Thanks!
Comments
Like this: B = -A
There's also an operator to do one's complement where you change 0's to 1's and vice versa. It's ~ (tilde), so you can do the two separate steps also.
Like this: B = ~A +1
The results are the same.
For example, the following snippet takes a number, then applies the ones compliment operator ~ (tilda) and then adds one to get the twos complement. That is just the negative of the number and could be written -N with the plain ordinary old minus sign. On output, the DEC modifier shows numbers as positive from 0 to 65535, whereas the SDEC modifier treats the number as twos complement from -32768 to +32767.
What more do you want to accomplish with it? PBASIC treats numbers as twos complement for operations of addition, subtraction and multiplication. Division and modulus are a separate issue.
I am using it to find the LRC for a Modbus ASCII message so I don't have to do anything fancy with it; just send it as a hex through the Serout command.
Sorry I didn't think to look in the manual.
Thanks!