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...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改