douzheng9221 2018-10-09 18:38
浏览 75
已采纳

binary.Read()在struct中不产生期望值

I'm trying to make a MOBI file parser and I'm running into a bit of an issue with trying to parse some of the binary into a struct with binary.Read().

I'm thinking it's an alignment issue, but I'm at a loss for why I'm not getting expected values. I've run the .mobi file through libmobi to test my code's output against, as well as inspected the binary of the .mobi in order to verify that I'm not crazy and the libmobi code wasn't doing something weird (which it's not).

Here's a stripped-down example:

package main

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

type Header struct {
    Type        [4]byte
    Creator     [4]byte
    Uid         uint32
    Next        uint32
    RecordCount uint16
}

func main() {
    testBytes := []byte{66, 79, 79, 75, 77, 79, 66, 73, 0, 0, 1, 17, 0, 0, 0, 0, 0, 136}

    h := Header{}
    buf := bytes.NewBuffer(testBytes)
    binary.Read(buf, binary.LittleEndian, &h)

    fmt.Printf("%s
", h.Type)    // BOOK, as expected
    fmt.Printf("%s
", h.Creator) // MOBI, as expected
    fmt.Printf("%d
", h.Next)    // 0, as expected

    fmt.Printf("%d
", h.Uid)
    // expecting Uid to be 273, but it's 285278208...
    fmt.Printf("%d
", h.RecordCount)
    // expecting RecordCount to be 136, but it's 34816...
}

Any help would be greatly appreciated!

EDIT: here are the hex bytes from doing a xxd on book.mobi:

424f 4f4b 4d4f 4249 0000 0111 0000 0000 0088

  • 写回答

1条回答 默认 最新

  • doujia9204 2018-10-09 19:16
    关注

    Yes BigEndian works much better

    package main
    
    import (
        "bytes"
        "encoding/binary"
        "fmt"
    )
    
    type Header struct {
        Type        [4]byte
        Creator     [4]byte
        Uid         uint32
        Next        uint32
        RecordCount uint16
    }
    
    func main() {
        testBytes := []byte{66, 79, 79, 75, 77, 79, 66, 73, 0, 0, 1, 17, 0, 0, 0, 0, 0, 136}
    
        h := Header{}
        buf := bytes.NewBuffer(testBytes)
        binary.Read(buf, binary.BigEndian, &h)
    
        fmt.Printf("%s
    ", h.Type)    // BOOK, as expected
        fmt.Printf("%s
    ", h.Creator) // MOBI, as expected
        fmt.Printf("%d
    ", h.Next)    // 0, as expected
    
        fmt.Printf("%d
    ", h.Uid)
        // expecting Uid to be 273, but it's 285278208...
        fmt.Printf("%d
    ", h.RecordCount)
        // expecting RecordCount to be 136, but it's 34816...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置