英文:
Equivalent of readUIntLE in Golang?
问题
我需要在缓冲区的位置Y读取X个字节。
在Node.js中,我使用Buffer类和readUIntLE函数来实现这个操作。
例如:readUIntLE(position, 3)
。
在Golang中,这个过程的等价方式是什么?
谢谢!
英文:
I need to read X (for example, 3) bytes at position Y in the buffer.
In Node.js, I'm doing this by using the Buffer class and the readUIntLE function.
For example: readUIntLE(position, 3)
.
What is the equivalent of that process in Golang?
Thanks!
答案1
得分: 3
例如,
package main
import "fmt"
func readUIntLE(buf []byte, offset, byteLength int) uint64 {
var n uint64
buf = buf[offset : offset+byteLength]
if len(buf) > 8 {
buf = buf[:8]
}
for i, b := range buf {
n += uint64(b) << uint(8*i)
}
return n
}
func main() {
buf := []byte{2, 4, 8, 16, 32, 64, 128, 255}
fmt.Println(buf)
fmt.Println(readUIntLE(buf, 0, 4))
fmt.Println(readUIntLE(buf, 0, len(buf)))
fmt.Println(readUIntLE(buf, len(buf)-1, 1))
}
输出:
[2 4 8 16 32 64 128 255]
268960770
18410785783142679554
255
英文:
For example,
package main
import "fmt"
func readUIntLE(buf []byte, offset, byteLength int) uint64 {
var n uint64
buf = buf[offset : offset+byteLength]
if len(buf) > 8 {
buf = buf[:8]
}
for i, b := range buf {
n += uint64(b) << uint(8*i)
}
return n
}
func main() {
buf := []byte{2, 4, 8, 16, 32, 64, 128, 255}
fmt.Println(buf)
fmt.Println(readUIntLE(buf, 0, 4))
fmt.Println(readUIntLE(buf, 0, len(buf)))
fmt.Println(readUIntLE(buf, len(buf)-1, 1))
}
Output:
[2 4 8 16 32 64 128 255]
268960770
18410785783142679554
255
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论