What's the syntax for creating a byte array in Clojure initialized to a specified collection of values?
Something like this, but that works...
(byte-array [0 1 2 3])
What's the syntax for creating a byte array in Clojure initialized to a specified collection of values?
Something like this, but that works...
(byte-array [0 1 2 3])
(byte-array (map byte [0 1 2 3]))
afaik Clojure has no byte literals.
Other posters have given good answers that work well.
This is just in case you are doing this a lot and want a macro to make your syntax a bit tidier:
(defmacro make-byte-array [bytes]
`(byte-array [~@(map (fn[v] (list `byte v)) bytes)]))
(aget (make-byte-array [1 2 3]) 2)
=> 3
(byte-array [(byte 0) (byte 1) (byte 2)])
Explanation:
byte creates a byte
byte-array creates a byte[]
bytes converts it to byte[]
byte coerces to byte, although in 1.2 all arguments to functions are autoboxed, so byte-array still receives Byte-s and needs to unbox them. Try (loop [i (byte 0)] (recur (Byte. 0))) at a 1.2 REPL to verify this.(class (byte 1)) it will yield java.lang.Byte because it was boxed when passed to class function, although (byte 1) was a primitive byte.