From 7572f6fc3d570ffb0dbc34d8673c755bafc7dc2c Mon Sep 17 00:00:00 2001 From: Peter Hinch Date: Fri, 17 Mar 2017 16:25:40 +0000 Subject: [PATCH] Python Bit Reversal code added. --- README.md | 3 ++- reverse/reverse.py | 24 ++++++++++++++++++++++-- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 8dff637..3e4d8f6 100644 --- a/README.md +++ b/README.md @@ -107,7 +107,8 @@ data in a manner which ensures data integrity. Access the simpler of the Pyboard's watchdog timers. # reverse -Fast reverse a bytearray. +Fast reverse a bytearray in Arm Thumb assembler. +Python code to bit-reverse (fast-ish) 8, 16 and 32 bit words. # ds3231_pb Driver for the DS3231 low cost precison RTC, including a facility to calibrate the Pyboard's RTC diff --git a/reverse/reverse.py b/reverse/reverse.py index 9e7fe52..9b7ce9f 100644 --- a/reverse/reverse.py +++ b/reverse/reverse.py @@ -11,7 +11,7 @@ def reverse(r0, r1): # bytearray, len(bytearray) sub(r4, 1) cmp(r4, r0) bpl(LOOP) - + def test(): a = bytearray([0, 1, 2, 3]) # even length reverse(a, len(a)) @@ -19,5 +19,25 @@ def test(): a = bytearray([0, 1, 2, 3, 4]) # odd length reverse(a, len(a)) print(a) - + +# Bit reverse an 8 bit value +def rbit8(v): + v = (v & 0x0f) << 4 | (v & 0xf0) >> 4 + v = (v & 0x33) << 2 | (v & 0xcc) >> 2 + return (v & 0x55) << 1 | (v & 0xaa) >> 1 + +# Bit reverse a 16 bit value +def rbit16(v): + v = (v & 0x00ff) << 8 | (v & 0xff00) >> 8 + v = (v & 0x0f0f) << 4 | (v & 0xf0f0) >> 4 + v = (v & 0x3333) << 2 | (v & 0xcccc) >> 2 + return (v & 0x5555) << 1 | (v & 0xaaaa) >> 1 + +# Bit reverse a 32 bit value +def rbit32(v): + v = (v & 0x0000ffff) << 16 | (v & 0xffff0000) >> 16 + v = (v & 0x00ff00ff) << 8 | (v & 0xff00ff00) >> 8 + v = (v & 0x0f0f0f0f) << 4 | (v & 0xf0f0f0f0) >> 4 + v = (v & 0x33333333) << 2 | (v & 0xcccccccc) >> 2 + return (v & 0x55555555) << 1 | (v & 0xaaaaaaaa) >> 1