Shop OBEX P1 Docs P2 Docs Learn Events
Bit Operations in Spin — Parallax Forums

Bit Operations in Spin

hylee101001hylee101001 Posts: 48
edited 2015-06-26 00:42 in Propeller 1
I wrote following code. But the result is little odd as commented below; it looks the data is larger than 16 bits..? Could someone explain this? Thank you.
Oh, the object I used here may not work though.. So please just put spaces at the object name and delete usb.newline. Or, use other serial object...

CON
_clkmode = xtal1 + pll16x
_xinfreq = 5_000_000

obj

usb : "ParallaxSerialTerminal.spin"

VAR

word x, one, zero, r, temp

PUB main
usb.quickstart
x := %1111_1111_0000_0101'_1111_1111_0000_0101
one := %1111_1111_1111_1111'_1111_1111_1111_1111
zero := %0000_0000_0000_0000'_0000_0000_0000_0000
temp := %0000_0000_0000_0000'_0000_0000_1111_1111

'r := x >> 8 << 8 ' outcome is as expected, 1111_1111_0000_0000
r := x << 8 >> 8 ' outcome is NOT as expected, 1111_1111_0000_0101
' I expected 0000_0000_0000_0101
repeat
usb.clear
usb.bin(r,32)
if (r>0)
usb.newline
usb.str(string("Least significant byte of x equlas 1"))
else
usb.newline
usb.str(string("Least significant byte of x NOT equlas 1"))
usb.newline


waitcnt(cnt + clkfreq/10)

Comments

  • Phil Pilgrim (PhiPi)Phil Pilgrim (PhiPi) Posts: 23,514
    edited 2015-06-25 18:50
    Although your variables are words, expressions are always evaluated as 32-bit signed integers.

    Also,

    attachment.php?attachmentid=78421&d=1297987572

    -Phil
  • Duane DegnDuane Degn Posts: 10,588
    edited 2015-06-25 18:56
    I gave up trying to use bit operations on anything but longs a long time ago.

    Some of the operations only work correctly on longs.
  • AribaAriba Posts: 2,682
    edited 2015-06-25 19:16
    If you write it like that it should result in what you expected:
    ...
    r := x << 8
    r := r >> 8
    ...
    

    so the intermediate result of the first shift is written into the 16bit variable.

    Andy
  • Dave HeinDave Hein Posts: 6,347
    edited 2015-06-25 19:18
    When you do "x << 8 >> 8" the value of x is promoted to a 32-bit value before it is shifted. The result you are seeing is expected since the 16-bit value is being shifted as 32 bits.
  • Phil Pilgrim (PhiPi)Phil Pilgrim (PhiPi) Posts: 23,514
    edited 2015-06-25 19:49
    To get what you want, do this:
    r := x << 24 >> 24

    or, more simply:
    r := x & $ff

    -Phil
  • kuronekokuroneko Posts: 3,623
    edited 2015-06-26 00:42
    ...
    r := x & $ff
    Alternatively one could use:
    r := x.byte[0]
    
Sign In or Register to comment.