Skip to content

Instantly share code, notes, and snippets.

@jtrim
Created February 2, 2012 03:54
Show Gist options
  • Select an option

  • Save jtrim/1721338 to your computer and use it in GitHub Desktop.

Select an option

Save jtrim/1721338 to your computer and use it in GitHub Desktop.
(ns bit-sandbox.core)
; helper
(defn shifted-byte [int-byte-value, shift-by]
(bit-shift-left
(bit-and int-byte-value 0xFF)
(* shift-by 8)))
; (+ meat potatoes)
;...clojure joke.
;
; Both versions of this function take a vector of number-represented bytes and
; turns the bytes into a number. e.g.
; (bytes-to-int [0 0 0 0]) ;=> 4-byte integer `0`
; (bytes-to-int [0 0 0 255]) ;=> 4-byte integer `255`
; (bytes-to-int [0 0 1 0]) ;=> 4-byte integer `256`
; etc...
; v1 uses loop/recur. At each level of recursion, the byte in question
; is shifted left a number corresponding to the number of bytes at
; that given level of recursion, then added to the running sum and either
; returned or passed down another level. See: http://inception.davepedu.com/
(defn bytes-to-int-v1 [vec-bytes]
(loop [sum 0, the-bytes vec-bytes]
(if (empty? the-bytes)
sum
(recur
(+ sum (shifted-byte (first the-bytes) (count (rest the-bytes))))
(rest the-bytes)))))
; v2 reduces the vector of bytes with an accumulator of [sum position] where:
; - sum: The running sum of shifted bytes
; - position: The zero-based index (note: from the right, not the left) of the
; current byte in the vector. Used to determine how many bits to left-shift
; the byte in question.
(defn bytes-to-int-v2 [vec-bytes]
(first (reduce
(fn [acc, the-byte]
[(+ (first acc) (shifted-byte the-byte (last acc))) (dec (last acc))])
[0 (dec (count vec-bytes))]
vec-bytes)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment