Shop OBEX P1 Docs P2 Docs Learn Events
Spin negative numbers?? — Parallax Forums

Spin negative numbers??

TJHJTJHJ Posts: 243
edited 2008-06-24 21:26 in Propeller 1
Ok so my math my not be the greatest but how can I allow and use negative numbers?
Currently if I use byte variables and store
X := 128 ' Fixed Value

NewX := 129 ' Updating Value but per example 129 works. 

Diffx := X-Newx 





If byte variables are used this gives 255
If word variables are used this gives 65544

I want the answer to be -1.... Well I want a lot of things but Ill start small.

The problem I think lies in telling the prop signed or unsigned number, but I cant seem to find a command to do this.

Thanks as always
TJ

Comments

  • Phil Pilgrim (PhiPi)Phil Pilgrim (PhiPi) Posts: 23,514
    edited 2008-06-24 21:06
    Only longs can be negative. Neither bytes nor words can be negative because they don't reach to the sign bit (31). That said, you can treat the high bit in either a byte or a word as the sign by some shiftery:

    (byte_var << 24 ~> 24) sign extends a byte in an expression.
    (word_var << 16 ~> 16) sign extends a word in an expression.

    -Phil

    Post Edited (Phil Pilgrim (PhiPi)) : 6/24/2008 9:13:35 PM GMT
  • Paul BakerPaul Baker Posts: 6,351
    edited 2008-06-24 21:10
    In 8 bit math 255 is -1, and in 16 bit math 65535 is -1 (are you sure you got 65544 as your answer?). The issue here is that you are doing math on a 32 bit computer, not a 8 or 16 bit computer. Now lets do 0-1 in 8 bit, the answer is $FF (255 unsigned, -1 signed), now that answer expressed in a 32 bit computer is $0000_00FF, which is (you guessed it) 255 in both signed and unsigned. In 32 bit -1 = $FFFF_FFFF not $0000_00FF, so what do you do? Use the sign extension command (~X for 8 bit, ~~X for 16 bit). What this does is take the sign bit (the most significant bit) and copies it across the remaining higher bits not used in the original computation. The resultant value will be the 32 bit signed version of the number, and the Propeller will correctly identify the value.

    ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
    Paul Baker
    Propeller Applications Engineer

    Parallax, Inc.
  • lonesocklonesock Posts: 917
    edited 2008-06-24 21:11
    Have you tried the sign extend operators? (~X) if X is a byte, or (~~X) if X is a word.
    edit: beat me to it [noparse][[/noparse]8^)

    ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
    lonesock
    Piranha are people too.
  • Phil Pilgrim (PhiPi)Phil Pilgrim (PhiPi) Posts: 23,514
    edited 2008-06-24 21:12
    Paul, you beat me to it. And on top of that I forgot about the shorthand sign-extension ops! blush.gif

    -Phil
  • TJHJTJHJ Posts: 243
    edited 2008-06-24 21:26
    No yes, Maybe, I doubt it.... Ummmm Thanks

    Cool, Sign operator should make this work, thanks again all.
Sign In or Register to comment.