(let [buffer (ByteBuffer/allocate 8)
arr (byte-array 2)]
(doto buffer
(.putLong 4)
(.get arr)))
-
3Can you elaborate on what your question is?Daniel Compton– Daniel Compton2015-05-05 08:29:49 +00:00Commented May 5, 2015 at 8:29
-
I got the question because I faced the same problem. Why people down vote without knowing?Mrinal Saurabh– Mrinal Saurabh2017-09-14 12:11:26 +00:00Commented Sep 14, 2017 at 12:11
Add a comment
|
1 Answer
It's not entirely clear what the question is, so here is an example of reading and writing from java.nio.ByteBuffer:
by bytes:
user> (let [buf-len 8
buffer (ByteBuffer/allocate buf-len)
arr (byte-array 2)]
(doseq [x (range buf-len)]
(.put buffer x (byte x)))
(.get buffer arr 0 (count arr))
(println "buffer contains"
(for [x (range buf-len)]
(.get buffer x)))
(println "arr contains" (vec arr)))
buffer contains (0 1 2 3 4 5 6 7)
arr contains [0 1]
nil
and by longs:
user> (let [buf-len 8
buffer (ByteBuffer/allocate buf-len)
arr (byte-array 2)]
(.putLong buffer 0 Long/MAX_VALUE)
(.get buffer arr)
(println "buffer contains"
(for [x (range buf-len)]
(.get buffer x)))
(println "arr contains" (vec arr)))
buffer contains (127 -1 -1 -1 -1 -1 -1 -1)
arr contains [127 -1]
nil
and your original example was very close, it just needed the offset:
user> (let [buffer (ByteBuffer/allocate 8)
arr (byte-array 2)]
(doto buffer
(.putLong 0 4)
(.get arr)))
#<HeapByteBuffer java.nio.HeapByteBuffer[pos=2 lim=8 cap=8]>