Created
November 15, 2015 06:14
-
-
Save kurogelee/0d789e7d499e7ce2b332 to your computer and use it in GitHub Desktop.
Clojureでバイト配列を整数に変換する ref: http://qiita.com/kurogelee/items/919cd0df8b59d7bcf65a
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
(def << bit-shift-left) | |
(def >> bit-shift-right) | |
(defn unsigned [^bytes bytea] | |
{:pre [(<= 1 (alength bytea) 7)]} | |
(areduce bytea i ret 0 | |
(bit-or (<< ret 8) (bit-and 0xff (aget bytea i))))) | |
(defn signed [^bytes bytea] | |
{:pre [(<= 1 (alength bytea) 8)]} | |
(areduce bytea i ret (if (neg? (aget bytea 0)) -1 0) | |
(bit-or (<< ret 8) (bit-and 0xff (aget bytea i))))) |
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
(defn areverse-byte [^bytes bytea] | |
(let [len (alength bytea)] | |
(areduce bytea i ret (byte-array len) | |
(do (aset-byte ret (- len i 1) (aget bytea i)) ret)))) |
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
(defn ^bytes ->bytes [^long len ^long value] | |
{:pre [(<= 1 len 8)]} | |
(byte-array | |
(reduce (fn [a i] (conj a (>> value (* (- len i 1) 8)))) [] (range len)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment