PDA

View Full Version : SWAP nibble



Coolguy
04-12-2007, 04:40 AM
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?

Chris Savage
04-12-2007, 05:00 AM
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 Allen
04-12-2007, 10:56 AM
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 (http://www.emesystems.com)

Chris Savage
04-12-2007, 09:42 PM
Tracy,

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

▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
Chris Savage
Parallax Tech Support

Coolguy
04-12-2007, 10:58 PM
Thank you both of you!

Tracy Allen
04-12-2007, 11:04 PM
Slightly shorter and faster as,


x = x << 4 | x.nib1

▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
Tracy Allen
www.emesystems.com (http://www.emesystems.com)