在Golang中,readUIntLE的等效函数是什么?

huangapple go评论92阅读模式
英文:

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 &quot;fmt&quot;

func readUIntLE(buf []byte, offset, byteLength int) uint64 {
	var n uint64
	buf = buf[offset : offset+byteLength]
	if len(buf) &gt; 8 {
		buf = buf[:8]
	}
	for i, b := range buf {
		n += uint64(b) &lt;&lt; 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

huangapple
  • 本文由 发表于 2015年5月10日 21:44:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/30152150.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定