1

I have a byte array, for example:

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

How do I get the size of it and how do I prepend this size to the g byte array?

3 Answers 3

3

alength will get you the size.

You'd have to make a new array to prepend it. Here goes:

(def g' (let [len (alength g)
              bs (byte-array (inc len))]
          (do (System/arraycopy g (int 0) bs (int 1) len)
              (aset bs (int 0) len)
              bs)))
Sign up to request clarification or add additional context in comments.

Comments

2

The prepending part can be done like this (probably not the best solution):

(def g (byte-array (apply #(cons (byte (count %)) %) [(map byte [0 1 2 3])])))

It returns:

[4, 0, 1, 2, 3]

I think that you should use (alength g) for the length of a Java array.

Of course if your byte array is longer than 255 you will have problems with adding the length as a single byte.

2 Comments

Maybe (byte-array (cons (-> g count byte) g))? Or (->> (cons (count g) g) (map byte) byte-array) if you need to cast everything?
May be like this: (def g (->> [0 1 2 3] (#(cons (count %) %)) (map byte) (byte-array)))
0

Not sure what you mean about prepending the size, but you can get the size using count

user=> (def g (byte-array (map byte [0 1 2 3])))
#'user/g
user=> (count g)
4

1 Comment

Thanks I mean to add the size to the beginning of the array. For google protocol buffers.

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.