0

node.js中的readUint16BE函数,函数声明为:

buf.readUInt16BE(offset, [noAssert])

文档: http ://nodejs.org/api/buffer.html#buffer_buf_readuint16be_offset_noassert

从缓冲区的指定偏移量处以指定的字节序格式读取一个无符号的 16 位整数。

如何在 golang 中实现?非常感谢

或 golang 有一些功能,如 readUint16BE ?

4

1 回答 1

4

您可以使用 encoding/binary 包。例如:(http://play.golang.org/p/5s_-hclYJ0

package main

import (
    "encoding/binary"
    "fmt"
)

func main() {
    buf := make([]byte, 1024)

    // Put uint16 320 (big endian) into buf at offster 127
    binary.BigEndian.PutUint16(buf[127:], 320)

    // Put uint16 420 (little endian) into buf at offster 127
    binary.LittleEndian.PutUint16(buf[255:], 420)

    // Retrieve the uint16 big endian from buf
    result := binary.BigEndian.Uint16(buf[127:])
    fmt.Printf("%d\n", result)

    // Retrieve the uint16 little endian from buf
    result = binary.LittleEndian.Uint16(buf[255:])
    fmt.Printf("%d\n", result)

    // See the state of buf (display only 2 bytes from the given often as it is uint16)
    fmt.Printf("%v, %v\n", buf[127:129], buf[255:257])
}
于 2013-09-24T20:38:55.260 回答