相当于Golang中的readUIntLE?

时间:2015-05-10 13:44:43

标签: node.js go

我需要在缓冲区中的位置Y读取X(例如,3)个字节。

在Node.js中,我通过使用Buffer类和readUIntLE函数来做到这一点。

例如:Int a = new Int (12); int x = a;

Golang中该流程的等效内容是什么?

谢谢!

1 个答案:

答案 0 :(得分: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