如何用clojure读取ByteBuffer中的字节?
how to read bytes in ByteBuffer with clojure?
(let [buffer (ByteBuffer/allocate 8)
arr (byte-array 2)]
(doto buffer
(.putLong 4)
(.get arr)))
不是很清楚问题是什么,所以这里有一个阅读和写作的例子来自java.nio.ByteBuffer:
字节数:
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
多头:
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
您的原始示例非常接近,它只需要偏移量:
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]>
(let [buffer (ByteBuffer/allocate 8)
arr (byte-array 2)]
(doto buffer
(.putLong 4)
(.get arr)))
不是很清楚问题是什么,所以这里有一个阅读和写作的例子来自java.nio.ByteBuffer:
字节数:
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
多头:
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
您的原始示例非常接近,它只需要偏移量:
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]>