英文:
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]) << 24 +
int32(packet.buffer[at+1]) << 16 +
int32(packet.buffer[at+2]) << 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 (
"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))
}
Output: 65535 9.1834e-41
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论