ccjeaty
ccjeaty

Reputation: 121

how to read bytes in ByteBuffer with clojure?

(let [buffer (ByteBuffer/allocate 8)
      arr (byte-array 2)]
   (doto buffer
      (.putLong 4)
      (.get arr)))

Upvotes: 0

Views: 2257

Answers (1)

Arthur Ulfeldt
Arthur Ulfeldt

Reputation: 91534

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

Upvotes: 4

Related Questions