Shop OBEX P1 Docs P2 Docs Learn Events
Two's compliment in PBasic? — Parallax Forums

Two's compliment in PBasic?

lindseydallaslindseydallas Posts: 14
edited 2014-04-08 11:39 in BASIC Stamp
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!

Comments

  • Mike GreenMike Green Posts: 23,101
    edited 2014-04-08 09:12
    A minus sign will do it. See page 105-106 of the reference manual.

    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.
  • Steph LindsaySteph Lindsay Posts: 767
    edited 2014-04-08 09:13
    I don't think there's a single command for that, but would the REV operator get you halfway there?
  • Steph LindsaySteph Lindsay Posts: 767
    edited 2014-04-08 09:13
    Thanks Mike!
  • Tracy AllenTracy Allen Posts: 6,664
    edited 2014-04-08 09:22
    There are quite a few twos compliment helpers in PBASIC.

    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.
    [SIZE=1][FONT=courier new]' {$STAMP BS2pe}
    ' {$PBASIC 2.5}
    
    N VAR WORD
    M VAR WORD
    
    Main:
      N = 12345
      M = ~N + 1   ' ones complement and add 1, same as negative N
      DEBUG CR, DEC M, CR, SDEC M, CR, SDEC M+N, CR[/FONT][/SIZE]
    


    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.
  • Mike GreenMike Green Posts: 23,101
    edited 2014-04-08 09:23
    REV reverses the order of the bits in the number, but doesn't otherwise change the bits. The reference manual has all the details. Make sure you have a copy on hand. You can download it here if you don't have a paper copy.
  • lindseydallaslindseydallas Posts: 14
    edited 2014-04-08 11:39
    LOVE simple solutions! The negative sign worked perfectly.
    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!
Sign In or Register to comment.