douchen7366 2015-01-02 10:20
浏览 109
已采纳

为什么binary.Read()无法正确读取整数?

I'm trying to read a binary file in Go.

Essentially I have a struct like this:

type foo struct {
    A int16
    B int32
    C [32]byte
    // and so on...
}

and I'm reading from the file into the struct like this:

fi, err := os.Open(fname)
// error checking, defer close, etc.
var bar foo
binary.Read(fi, binary.LittleEndian, &bar)

Now, that should work, but I'm getting some weird results. For instance, when I read into the struct I should get this:

A: 7
B: 8105
C: // some string

but what I get is this:

A: 7
B: 531169280
C: // some correct string

The reason for this is because when binary.Read() is reading the file, after it reads the []byte{7, 0} as int16(7) (the correct value for A), it comes across the slice []byte{0, 0, 169, 31} and tries to convert it into an int32. However, binary.Read()'s conversion does this:

uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 where b is the byte slice.

But what really confuses me is doing the exact same thing in C works perfectly fine.

If I write this in C:

int main()
{
    int fd;
    struct cool_struct {
        short int A;
        int32_t B;
        char C[32];
        // you get the picture...
    } foo;
    int sz = sizeof(struct cool_struct);
    const char* file_name = "/path/to/my/file"

    fd = open(file_name, O_RDONLY);
    // more code
    read(fd, &foo, sz);
    // print values
}

I get the correct results. Why is my C code getting this correct while my Go code isn't?

  • 写回答

2条回答 默认 最新

  • duanbei8904 2015-01-02 10:30
    关注

    Assuming the first two characters of the string aren't '\000'

    what you've got there is an alignment problem, your C compiler is putting an extra two bytes of padding after the int16, Go isn't

    easiest fix is probably just to add a dummy (padding) int16 after 'A'

    type foo struct 
    {
        A int16
        A_pad int16
        B int32
        C [32]byte
    }
    

    or the may be a way to tell go that the int32 needs to be "4-byte aligned"

    if you know of one please edit this answer or post a comment

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测