字节切片操作

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

Byte slice manipulation

问题

我正在编写一个程序,应该解析和回复网络数据包,但我有点烦恼,因为我不能像在C语言中那样简单地使用return (int)buffer[at];来处理字节数组。有没有比下面这种方法更好的方式从byte[]中获取4个字节作为int32呢?

func (packet *Packet) GetInt32(at int) int32 {
    return int32(packet.buffer[at]) << 24 +
        int32(packet.buffer[at+1]) << 16 +
        int32(packet.buffer[at+2]) << 8 +
        int32(packet.buffer[at+3])
}

它可以正常工作,但我在想是否有更好的方法来实现这个功能。

英文:

I'm writing a program that should parse and reply to network packets but I'm a bit annoyed because I can't do simple C style return (int)buffer[at]; with an array of bytes. Is there any better way to retrieve 4 bytes from byte[] as int32 than the following?

func (packet *Packet) GetInt32(at int) int32 {
	return int32(packet.buffer[at]) &lt;&lt; 24 +
		int32(packet.buffer[at+1]) &lt;&lt; 16 +
		int32(packet.buffer[at+2]) &lt;&lt; 8 +
		int32(packet.buffer[at+3])
}

It works correctly but I was thinking if there was a better way to do this.

答案1

得分: 2

包 main

import (
"encoding/binary"
"fmt"
"math"
)

type Packet struct {
buffer []byte
}

func (p *Packet) Int32(i int) int32 {
return int32(binary.BigEndian.Uint32(p.buffer[i : i+4]))
}

func (p *Packet) Float32(i int) float32 {
return math.Float32frombits(binary.BigEndian.Uint32(p.buffer[i : i+4]))
}

func main() {
p := &Packet{buffer: []byte{0x01, 0x02, 0x00, 0x00, 0xFF, 0xFF, 0x07}}
fmt.Println(p.Int32(2), p.Float32(2))
}

输出:65535 9.1834e-41

英文:
package main

import (
	&quot;encoding/binary&quot;
	&quot;fmt&quot;
	&quot;math&quot;
)

type Packet struct {
	buffer []byte
}

func (p *Packet) Int32(i int) int32 {
	return int32(binary.BigEndian.Uint32(p.buffer[i : i+4]))
}

func (p *Packet) Float32(i int) float32 {
	return math.Float32frombits(binary.BigEndian.Uint32(p.buffer[i : i+4]))
}

func main() {
	p := &amp;Packet{buffer: []byte{0x01, 0x02, 0x00, 0x00, 0xFF, 0xFF, 0x07}}
	fmt.Println(p.Int32(2), p.Float32(2))
}


Output:  65535  9.1834e-41

huangapple
  • 本文由 发表于 2010年12月25日 05:20:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/4528385.html
匿名

发表评论

匿名网友

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

确定