how to implement a readUInt16BE function in node.js

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

how to implement a readUInt16BE function in node.js

问题

在Node.js中,readUint16BE函数的声明如下:

buf.readUInt16BE(offset, [noAssert])

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

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

在Golang中如何实现这个功能?非常感谢!

或者Golang中是否有类似readUint16BE的函数?

英文:

The readUint16BE function in node.js, the function declare is:

buf.readUInt16BE(offset, [noAssert])

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

> Reads an unsigned 16 bit integer from the buffer at the specified offset with specified endian format.

how to implement in golang? thanks very much

or golang have some function like readUint16BE ??

答案1

得分: 4

你可以使用encoding/binary包进行编码。以下是示例代码:

package main

import (
	"encoding/binary"
	"fmt"
)

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

	// 将uint16类型的数字320(大端序)放入buf的偏移量为127的位置
	binary.BigEndian.PutUint16(buf[127:], 320)

	// 将uint16类型的数字420(小端序)放入buf的偏移量为255的位置
	binary.LittleEndian.PutUint16(buf[255:], 420)

	// 从buf中获取大端序的uint16数字
	result := binary.BigEndian.Uint16(buf[127:])
	fmt.Printf("%d\n", result)

	// 从buf中获取小端序的uint16数字
	result = binary.LittleEndian.Uint16(buf[255:])
	fmt.Printf("%d\n", result)

	// 查看buf的状态(仅显示给定偏移量的2个字节,因为它是uint16类型)
	fmt.Printf("%v, %v\n", buf[127:129], buf[255:257])
}

这段代码演示了如何使用encoding/binary包进行编码和解码操作。它将一个uint16类型的数字以大端序和小端序的方式存储到一个字节切片中,并从中提取出这两个数字。最后,它展示了buf的状态,显示了给定偏移量的2个字节。

英文:

You can use the encoding/binary package.
Ex: (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])
}

huangapple
  • 本文由 发表于 2013年9月25日 03:44:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/18990655.html
匿名

发表评论

匿名网友

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

确定