13

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])

1
  • 1
    your sample does work in later versions of clojure (tested in 1.8). Not sure when it changed. Commented Apr 11, 2017 at 13:34

4 Answers 4

15

(byte-array (map byte [0 1 2 3]))

afaik Clojure has no byte literals.

Sign up to request clarification or add additional context in comments.

1 Comment

Correct; as of Clojure 1.5, it does not have a byte literal: clojure.org/reader
4

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

1 Comment

A function would work just as well, right? This answer breaks the first rule of Macro Club: Don't Write Macros!
1
(byte-array [(byte 0x00) (byte 0x01) (byte 0x02) (byte 0x03)])

Comments

1
(byte-array [(byte 0) (byte 1) (byte 2)])

Explanation:

byte creates a byte

byte-array creates a byte[]

bytes converts it to byte[]

5 Comments

byte-array creates byte[], so the call to bytes is not needed.
You are right. Repl automatically boxing primitives got me confused. Corrected
In fact, 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.
Ok, so if I'm testing the type with (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.
Is the following garbage? (class (byte-array [(byte 0) (byte 1) (byte 2)])) which gives strange [B in the repl output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.