Skip to content

Instantly share code, notes, and snippets.

@appblue
Last active May 12, 2024 10:14
Show Gist options
  • Save appblue/0a8a617bf388b192fa6038685c11638a to your computer and use it in GitHub Desktop.
Save appblue/0a8a617bf388b192fa6038685c11638a to your computer and use it in GitHub Desktop.
Clojure - generating binary data big/little endian
(defn get-nth-byte [v n]
(bit-and 0xff (bit-shift-right v (* 8 n))))
(defn pack-little-endian [v n]
(let [l []]
(for [i (range n)]
(into (get-nth-byte v i) l))))
(defn pack-big-endian [v n]
(let [l []]
(for [i (range n)]
(into (get-nth-byte v (- n 1 i)) l))))
;; core> (pack-vector pack-big-endian 2 [16384 16385])
;; [64 0 64 1]
(defn pack-vector [f n xs]
(reduce (fn [l e]
(reduce conj l (f e n)))
[]
xs))
(defn gen-sin [n a t]
(for [i (range n)]
(int (+ t
(* a
(Math/sin
(* i (/ (* 2 Math/PI) n))))))))
;; core> (save-sin "sin.dat" 2 128 32767 32768)
;; core> (save-sin "sin.dat" 2 128 32767 32768 :big-endian true)
;; core> (save-sin "sin.dat" 2 128 32767 32768 :big-endian false)
(defn save-sin
"Writes a sin table to a file named [fname] with each value encoded as
big-endian (default) or little-endian (based on a key parameter)
in [sz] bytes. Sinus table is [n] values long with amplitude [a] and
offset [t]"
[fname sz n a t & {:keys [big-endian] :or {big-endian true}}]
(let [packfn (if big-endian pack-big-endian pack-little-endian)]
(with-open [w (clojure.java.io/output-stream fname)]
(->>
(gen-sin n a t)
(pack-vector packfn sz)
(byte-array)
(.write w)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment