Created
September 22, 2011 17:01
-
-
Save pingles/1235344 to your computer and use it in GitHub Desktop.
Clojure code to convert a byte array to an integer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn bytes-to-int | |
([bytes] | |
(bytes-to-int bytes 0)) | |
([bytes offset] | |
(reduce + 0 | |
(map (fn [i] | |
(let [shift (* (- 4 1 i) | |
8)] | |
(bit-shift-left (bit-and (nth bytes (+ i offset)) | |
0x000000FF) | |
shift))) | |
(range 0 4))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I thought bytebuffer wrapping method maybe slower than reduce, but criterium benchmark shows it's nearly 5x faster for one int. When treating with an array of 32 bytes containing 8 int, I found that wrapping 8 times is far more fast than wrapping the whole byte array into one java.nio.ByteBuffer then calling
(.getInt bytebuf offset)
with offset equals(range 0 8)
. Am I missing some key properties of java.nio.Bytebuffer? Thx.