python读取二进制文件_读取二进制文件到一个Python结构(Reading a binary file into a st...

发表评论

import struct

首先刚才读的二进制到一个数组

mbr = file('mbrcontent', 'rb').read()

所以,你可以获取一些片阵列的

partition_table = mbr[446:510]

然后它解为一个整数

signature = struct.unpack('

一个更复杂的例子

little_endian = (signature == 0xaa55) # should be True

print "Little endian:", little_endian

PART_FMT = (little_endian and '<' or '>') + (

"B" # status (0x80 = bootable (active), 0x00 = non-bootable)

# CHS of first block

"B" # Head

"B" # Sector is in bits 5; bits 9 of cylinder are in bits 7-6

"B" # bits 7-0 of cylinder

"B" # partition type

# CHS of last block

"B" # Head

"B" # Sector is in bits 5; bits 9 of cylinder are in bits 7-6

"B" # bits 7-0 of cylinder

"L" # LBA of first sector in the partition

"L" # number of blocks in partition, in little-endian format

)

PART_SIZE = 16

fmt_size = struct.calcsize(PART_FMT)

# sanity check expectations

assert fmt_size == PART_SIZE, "Partition format string is %i bytes, not %i" % (fmt_size, PART_SIZE)

def cyl_sector(sector_cyl, cylinder7_0):

sector = sector_cyl & 0x1F # bits 5-0

# bits 7-6 of sector_cyl contain bits 9-8 of the cylinder

cyl_high = (sector_cyl >> 5) & 0x03

cyl = (cyl_high << 8) | cylinder7_0

return sector, cyl

#I have corrected the indentation, but the change is refused because less than 6 characters, so I am adding this useful comment.

for partition in range(4):

print "Partition #%i" % partition,

offset = PART_SIZE * partition

(status, start_head, start_sector_cyl, start_cyl7_0, part_type, end_head, end_sector_cyl, end_cyl7_0,

lba, blocks ) = struct.unpack( PART_FMT,partition_table[offset:offset + PART_SIZE])

if status == 0x80:

print "Bootable",

elif status:

print "Unknown status [%s]" % hex(status),

print "Type=0x%x" % part_type

start = (start_head,) + cyl_sector(start_sector_cyl, start_cyl7_0)

end = (end_head,) + cyl_sector(end_sector_cyl, end_cyl7_0)

print " (Start: Heads:%i\tCyl:%i\tSect:%i)" % start

print " (End: Heads:%i\tCyl:%i\tSect:%i)" % end

print " LBA:", lba

print " Blocks:", blocks

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值