0
(let [buffer (ByteBuffer/allocate 8)
      arr (byte-array 2)]
   (doto buffer
      (.putLong 4)
      (.get arr)))
2
  • 3
    Can you elaborate on what your question is? Commented May 5, 2015 at 8:29
  • I got the question because I faced the same problem. Why people down vote without knowing? Commented Sep 14, 2017 at 12:11

1 Answer 1

4

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]>
Sign up to request clarification or add additional context in comments.

Comments

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.