如何在node.js中实现readUInt16BE函数

时间:2013-09-24 19:44:55

标签: javascript node.js go byte

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

buf.readUInt16BE(offset, [noAssert])

DOC: http://nodejs.org/api/buffer.html#buffer_buf_readuint16be_offset_noassert

  

使用指定的endian格式从指定偏移量的缓冲区中读取无符号16位整数。

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

或golang有一些函数,比如readUint16BE ??

1 个答案:

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