如何在Golang的字节缓冲区中解压各种形式的整数? [英] How do I unpack various form of integers in a byte buffer in Golang?
本文介绍了如何在Golang的字节缓冲区中解压各种形式的整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在字节缓冲区中提取各种字段。我想出了这个解决方案:
I need to extract various fields in a byte buffer. I came up with this solution:
func (fs *FileSystem) readSB() {
// fs.f is a *os.File
buf := make([]byte, 1024)
fs.f.ReadAt(buf, 1024)
// Offset: type
var p *bytes.Buffer
// 0: uint32
p = bytes.NewBuffer(buf[0:])
binary.Read(p, binary.LittleEndian, &fs.sb.inodeCount)
// 4: uint32
p = bytes.NewBuffer(buf[4:])
binary.Read(p, binary.LittleEndian, &fs.sb.blockCount)
// 20: uint32
p = bytes.NewBuffer(buf[20:])
binary.Read(p, binary.LittleEndian, &fs.sb.firstDataBlock)
// 24: uint32
p = bytes.NewBuffer(buf[24:])
binary.Read(p, binary.LittleEndian, &fs.sb.blockSize)
fs.sb.blockSize = 1024 << fs.sb.blockSize
// 32: uint32
p = bytes.NewBuffer(buf[32:])
binary.Read(p, binary.LittleEndian, &fs.sb.blockPerGroup)
// 40: uint32
p = bytes.NewBuffer(buf[40:])
binary.Read(p, binary.LittleEndian, &fs.sb.inodePerBlock)
}
是否有更好的/惯用的/直接的方式来做到这一点?
Is there a more better/idiomatic/straightforward way of doing this?
- 我希望保持显式偏移量
- 我想从字节缓冲区读取数据,而不是从文件中读取和读取如果可能的话。
推荐答案
您可以避免每次使用 .Next()
跳过字节你不想阅读:
You could avoid creating a new buffer every time by using .Next()
to skip the bytes you don't want to read:
{
// Offset: type
p := bytes.NewBuffer(buf)
// 0: uint32
binary.Read(p, binary.LittleEndian, &fs.sb.inodeCount)
// 4: uint32
binary.Read(p, binary.LittleEndian, &fs.sb.blockCount)
// Skip [8:20)
p.Next(12)
// 20: uint32
binary.Read(p, binary.LittleEndian, &fs.sb.firstDataBlock)
// 24: uint32
binary.Read(p, binary.LittleEndian, &fs.sb.blockSize)
fs.sb.blockSize = 1024 << fs.sb.blockSize
// Skip [28:32)
p.Next(4)
// 32: uint32
binary.Read(p, binary.LittleEndian, &fs.sb.blockPerGroup)
// Skip [36:40)
p.Next(4)
// 40: uint32
binary.Read(p, binary.LittleEndian, &fs.sb.inodePerBlock)
}
或者你可以避免用chunk来读块,并创建一个你直接用 binary.Read
读取的头结构:
Or you could avoid reading chunk by chunk and create a header structure which you read directly using binary.Read
:
type Head struct {
InodeCount uint32 // 0:4
BlockCount uint32 // 4:8
Unknown1 uint32 // 8:12
Unknown2 uint32 // 12:16
Unknown3 uint32 // 16:20
FirstBlock uint32 // 20:24
BlockSize uint32 // 24:28
Unknown4 uint32 // 28:32
BlocksPerGroup uint32 // 32:36
Unknown5 uint32 // 36:40
InodesPerBlock uint32 // 40:44
}
func main() {
var header Head
err = binary.Read(file, binary.LittleEndian, &header)
if err != nil {
log.Fatal(err)
}
log.Printf("%#v\n", header)
}
这篇关于如何在Golang的字节缓冲区中解压各种形式的整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文