1 回答

TA貢獻1798條經驗 獲得超3個贊
您可以使用編碼/二進制
來讀/寫固定大小的結構。此方法是可移植的,不依賴于內存布局、編譯器或 CPU 體系結構。例如:
// Note: using uint32 instead of time.Time for decoding.
// Convert to time.Time afterwards if needed.
type MVHD struct {
Version byte
Flags [3]byte
DateCreatedSecs uint32
DateModifiedSecs uint32
TimeUnit uint32 // time unit per second (default = 600)
DurationInUnits uint64 // time length (in time units)
}
// ..or use binary.BigEndian - whichever is correct for your data.
var endian = binary.LittleEndian
func decode(rd io.Reader) (*MVHD, error) {
var header MVHD
if err := binary.Read(rd, endian, &header); err != nil {
return nil, err
}
return &header, nil
}
用于將 轉換為 .這將允許您使用 mmap 數據。bytes.NewReader[]byteio.Readerdecode
或者,您可以手動對其進行解碼:
func decode2(buf []byte) (*MVHD, error) {
if len(buf) < 24 {
return nil, errors.New("not enough data")
}
return &MVHD{
Version: buf[0],
Flags: [3]byte{buf[1], buf[2], buf[3]},
DateCreatedSecs: binary.LittleEndian.Uint32(buf[4:8]),
DateModifiedSecs: binary.LittleEndian.Uint32(buf[8:12]),
TimeUnit: binary.LittleEndian.Uint32(buf[12:16]),
DurationInUnits: binary.LittleEndian.Uint64(buf[16:24]),
}, nil
}
同樣,您可以使用二進制文件就地更新數據。字節順序調用:Put
func updateDateModified(buf []byte, t uint32) error {
if len(buf) < 12 {
return errors.New("not enough data")
}
binary.LittleEndian.PutUint32(buf[8:12], t)
return nil
}
- 1 回答
- 0 關注
- 151 瀏覽
添加回答
舉報