Shop OBEX P1 Docs P2 Docs Learn Events
How to chane sign of var from + to - — Parallax Forums

How to chane sign of var from + to -

AGCBAGCB Posts: 327
edited 2014-01-06 19:19 in General Discussion
Probably a dumb question.
I want to enter a method w/ a negative value. The calling method does not support negative numbers .

IE I need to get -5 from +5
Simply negating subtracts from zero(256) and leaves 251.

I've tried every way I can think of. I'm using SPIN

Thanks
Aaron

Comments

  • Martin_HMartin_H Posts: 4,051
    edited 2014-01-06 09:06
    Isn't negation a urinary operator? So you would use syntax like the following:

    var := -var
  • Dave HeinDave Hein Posts: 6,347
    edited 2014-01-06 09:16
    It sounds like you're trying to negate a byte variable, which has a range from 0 to 255. You need to use a long variable to support negative numbers.
  • AGCBAGCB Posts: 327
    edited 2014-01-06 09:21
    I still get 251

    xnew:=5
    xnew1:=-xnew
  • AGCBAGCB Posts: 327
    edited 2014-01-06 09:23
    I didn't read the last part of your post about the LONG var.

    That did it!
    Thanks much
  • Duane DegnDuane Degn Posts: 10,588
    edited 2014-01-06 09:25
    Martin_H wrote: »
    Isn't negation a urinary operator? So you would use syntax like the following:

    var := -var

    In Spin you just need;
    -var
    
  • ZetsuZetsu Posts: 186
    edited 2014-01-06 13:44
    Couldn't you also just multiply the value by (-1) ? and to go backwards do the same again ? In Lou of the (cleaner looking) negation operator obviously.
  • Duane DegnDuane Degn Posts: 10,588
    edited 2014-01-06 13:50
    Zetsu wrote: »
    Couldn't you also just multiply the value by (-1) ? and to go backwards do the same again ? In Lou of the (cleaner looking) negation operator obviously.

    Yes, but negatives only work with longs.

    This one of the reasons from the sign extend operator "~" (when used on left side of a variable) in Spin. It can convert a 16-bit negative number (like those read from a sensor) into a full 32-bit negative which will behave properly when doing math in Spin.

    In generally, I try to use longs if I'm going to being do much math with the variable.
  • localrogerlocalroger Posts: 3,451
    edited 2014-01-06 19:19
    When you store a negative value in a byte, it gets truncated. This leaves it a positive byte value when you treat it as a long (which all math operations do).

    This is one of those very useful but weird and nonstandard things about Spin. Remember the hated ~ operator that clears or sets vars when used postfix? Used prefix, it extends the sign of a short variable to 32 bits for this sort of thing.

    ~bytevar = sign-extended byte variable value
    ~~wordvar = sign-extended word variable value

    These take the high bit of the byte or word and extend that bit through the rest of the 32-bit value to make something that will work with signed 32-bit arithmetic.
Sign In or Register to comment.