Created
February 22, 2011 23:22
-
-
Save sritchie/839651 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| ;; Okay, here's some practice. This might be a good candidate for a macro. | |
| (defn little-int | |
| "Converts four input bits to an int, in little endian format." | |
| [b0 b1 b2 b3] | |
| (bit-or | |
| (bit-shift-left b3 24) | |
| (bit-or | |
| (bit-shift-left (bit-and b2 0xff) 16) | |
| (bit-or | |
| (bit-shift-left (bit-and b1 0xff) 8) | |
| (bit-and b0 0xff))))) | |
| (defn little-long | |
| "Converts eight input bits to a long, in little endian format." | |
| [b0 b1 b2 b3 b4 b5 b6 b7] | |
| (bit-or | |
| (bit-shift-left b7 56) | |
| (bit-or | |
| (bit-shift-left (bit-and b6 0xff) 48) | |
| (bit-or | |
| (bit-shift-left (bit-and b5 0xff) 40) | |
| (bit-or | |
| (bit-shift-left (bit-and b4 0xff) 32) | |
| (bit-or | |
| (bit-shift-left (bit-and b3 0xff) 24) | |
| (bit-or | |
| (bit-shift-left (bit-and b2 0xff) 16) | |
| (bit-or | |
| (bit-shift-left (bit-and b1 0xff) 8) | |
| (bit-and b0 0xff))))))))) | |
| (defn flipped-endian-float | |
| "Flips the endian order of the supplied byte sequence, and converts it to float." | |
| [bitseq] | |
| (->> bitseq | |
| (map-indexed (fn [idx bit] | |
| (bit-shift-left | |
| (bit-and bit 0xff) | |
| (* 8 idx)))) | |
| (reduce +) | |
| (Float/intBitsToFloat))) | |
| ;; same as above, with commas to show where the previous expression is threaded in. | |
| (defn flipped-endian-float | |
| "Flips the endian order of the supplied byte sequence, and converts it to float." | |
| [bitseq] | |
| (->> bitseq | |
| (map-indexed (fn [idx bit] | |
| (bit-shift-left | |
| (bit-and bit 0xff) | |
| (* 8 idx))) ,,,) | |
| (reduce + ,,,) | |
| (Float/intBitsToFloat ,,,))) | |
| ;; unthreaded version | |
| (defn flipped-endian-float | |
| "Flips the endian order of the supplied byte sequence, and converts | |
| the sequence into a float." | |
| [bitseq] | |
| (Float/intBitsToFloat | |
| (reduce + (map-indexed (fn [idx bit] | |
| (bit-shift-left | |
| (bit-and bit 0xff) | |
| (* 8 idx))) | |
| bitseq)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment