Shop OBEX P1 Docs P2 Docs Learn Events
SWAP nibble — Parallax Forums

SWAP nibble

CoolguyCoolguy Posts: 26
edited 2007-04-12 16:04 in BASIC Stamp
What is the most optimal and efficient way to swap lower nibble with higher nibble in a byte? I don’t think PBASIC have a swap function, does it?

Comments

  • Chris SavageChris Savage Parallax Engineering Posts: 14,406
    edited 2007-04-11 22:00
    Here is one possible way to do it...Note that the value starts in x and ends in y, but you could easily put it back into x by adding x = y before the DEBUG and displaying x instead.· Take Care.
    ' {$STAMP BS2}
    ' {$PBASIC 2.5}
    x   VAR   Byte
    y   VAR   Byte
    x = %11111001
    y = x >> 4
    y.NIB1 = x.NIB0
    DEBUG BIN y
    

    ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
    Chris Savage
    Parallax Tech Support
  • Tracy AllenTracy Allen Posts: 6,664
    edited 2007-04-12 03:56
    It can be done in place so that it doesn't require a helper variable.
    x = x.nib0 << 4 | x.nib1
    

    ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
    Tracy Allen
    www.emesystems.com
  • Chris SavageChris Savage Parallax Engineering Posts: 14,406
    edited 2007-04-12 14:42
    Tracy,

    I knew you would have a more clever way of doing it… =)

    ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
    Chris Savage
    Parallax Tech Support
  • CoolguyCoolguy Posts: 26
    edited 2007-04-12 15:58
    Thank you both of you!
  • Tracy AllenTracy Allen Posts: 6,664
    edited 2007-04-12 16:04
    Slightly shorter and faster as,
    x = x << 4 | x.nib1
    

    ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
    Tracy Allen
    www.emesystems.com
Sign In or Register to comment.