字节序问题

今天使用Python来读取二进制文件。直接使用read读取,读入的内容没有错误,长度也是对的,使用了type函数查看了一下内存中的数据类型,发现是str的,初步认为是采用C语言里面的char方式存储。


不过我是要把读入的内容转为内存中的数据结构,需要处理整型等数据类型。由于自己认为是char方式存储的,就直观的认为只要将4个字节的char使用int()函数强制转换一下就没有问题的,不过转换失败。后来咨询了木头,说是要使用struct来处理。查手册,发现struct狠简单,常用的函数就是pack和unpcak。使用unpack函数试试,先google一下,网上面有没有相关的例子代码,发现一个:
print struct.unpack(‘>I’,recv_data[recv_len-6:recv_len-2])[0]
然后就照猫画虎写了一个
(“%s”)%struct.unpack(“>I”, buff[462:466])
不过测试结果却出乎我的意料,读出来的数据不对。同时对>号感到奇怪,查手册struct的下半部分,发现>是表示网络字节序方式,而不是我们x86系列的本地字节序,删除>试试,读出来的结果正确。


以前只是在写网络程序的时候要注意网络字节序问题,现在突然发现,python里面也要考虑字节序,看来python的处理考虑的还是狠周到的。不过以后也要注意二进制的字节序问题了,毕竟网络过来的二进制数据会越来越多的,很多程序中应该考虑这个问题。

This entry was posted in Python. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word