Skip to content

Instantly share code, notes, and snippets.

@yantonov
Last active December 10, 2015 01:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yantonov/4359090 to your computer and use it in GitHub Desktop.
Save yantonov/4359090 to your computer and use it in GitHub Desktop.
Reverse binary representation of 8 (16) bit numbers
(ns bitrev
(use clojure.test))
;; http://dolzhenko.blogspot.ru/2012/12/blog-post.html
;; reverse binary representation of 8 bit number
;; reverse binary representation of 16 bit number
(defn reverse-8bit
"reverse 8 bit number"
[n]
;;; x = (x & 0x55) << 1 | (x & 0xaa) >> 1
;;; reverse 1 bit and its neighbours
;;; x = (x & 0x33) << 2| (x & 0xcc) >> 2
;;; reverse 2 bits and its neighbours
;;; x = (x & 0x0f) << 4 | (x & 0xf0) >> 4
;;; reverse 2 bits and its neighbours
(let [x0 n
x1 (bit-or (bit-shift-left (bit-and x0 0x55) 1)
(bit-shift-right (bit-and x0 0xaa) 1))
x2 (bit-or (bit-shift-left (bit-and x1 0x33) 2)
(bit-shift-right (bit-and x1 0xcc) 2))
x4 (bit-or (bit-shift-left (bit-and x2 0x0f) 4)
(bit-shift-right (bit-and x2 0xf0) 4))]
x4))
(defn reverse-16bit
"reverse 16 bit number"
[n]
(let [x0 n
x1 (bit-or (bit-shift-left (bit-and x0 0x5555) 1)
(bit-shift-right (bit-and x0 0xaaaa) 1))
x2 (bit-or (bit-shift-left (bit-and x1 0x3333) 2)
(bit-shift-right (bit-and x1 0xcccc) 2))
x4 (bit-or (bit-shift-left (bit-and x2 0x0f0f) 4)
(bit-shift-right (bit-and x2 0xf0f0) 4))
x8 (bit-or (bit-shift-left (bit-and x4 0x00ff) 8)
(bit-shift-right (bit-and x4 0xff00) 8))]
x8))
(deftest reverse-8bit-test
(are [n result]
(= result (reverse-8bit n))
123 222
0 0
1 128
3 192
255 255
0x33 0xcc
0xf0 0x0f))
(deftest reverse-16bit-test
(are [n result]
(= result (reverse-16bit n))
0 0
1 0x8000
3 0xc000
0xff 0xff00
0x193a 0x5c98))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment