gpt4 book ai didi

python - 如何从二进制文件中读取 block 并使用 Python 或 Perl 解包提取结构?

转载 作者:行者123 更新时间:2023-11-28 20:26:33 28 4
gpt4 key购买 nike

我有一个二进制文件,它有 4 KB 的标题信​​息,然后是 28 字节的数据,然后是我想读取的 24 字节。我如何每 24 和 28 字节循环一次并读取(或提取)这 28 和 24 字节数据的前 8 个字节。在 python 中我做了这样的事情。不确定如何处理可变长度

import sys
import struct
f = open(sys.argv[1],"rb")
f.seek(4096)
byte = f.read(28)
while byte != "":
ticks = struct.unpack("<ll",byte[:8]) #not sure how to read 8 bytes
byte = f.read(28)
f.close()

这是标题后的样子。

Length
(bytes) Field Name
8 TS_INCR
4 SEQID
2 OP
2 LUN
4 NBLKS
8 LBA


Length
(bytes) Field Name
8 TS_INCR
4 SEQID
2 OP
2 LUN
4 LATENCY_TICKS
2 HOST_ID
2 HOST_LUN

如果你们能帮忙解决这个问题,请。 Python 或 PERL 无关紧要。谢谢!!!!!!

最佳答案

Endianness您正在阅读的数据在这里很重要。您似乎将 8 个八位字节解包为两个以小端顺序存储的 long。您确定它不是单个 64 位数量(这会使 qQ 格式更合适)?不幸的是,我在 32 位机器上,所以我的 perl 不支持 Q

但是,以下应该为您指明正确的方向:

#!/usr/bin/env perl

use strict; use warnings;
use autodie;

use Fcntl qw(:seek);
use List::Util qw( sum );

my ($input_file) = @ARGV;
die "Need input file\n" unless defined $input_file;

my $HEADER_SIZE = 4_096;

my @typedef = (
{
fields => [
qw(
TS_INCR_LO
TS_INCR_HI
SEQID
OP
LUN
NBLKS
LBA_LO
LBA_HI
)
],
tmpl => 'LLLSSLLL',
start => 0,
size => 28,
},
{
fields => [
qw(
TS_INCR_LO
TS_INCR_HI
SEQID
OP
LUN
LATENCY_TICKS
HOST_ID
HOST_LUN
)
],
tmpl => 'LLLSSLSS',
start => 28,
size => 24,
},
);

open my $input, '<:raw', $input_file;

seek $input, $HEADER_SIZE, SEEK_SET;

my $BLOCK_SIZE = sum map $_->{size}, @typedef;
read $input, my($buffer), $BLOCK_SIZE;

my @structs;

for my $t ( @typedef ) {
my %struct;
@struct{ @{ $t->{fields}} } = unpack(
$t->{tmpl},
substr($buffer, $t->{start}, $t->{size})
);
push @structs, \%struct;
}

use Data::Dumper;
print Dumper \@structs;

关于python - 如何从二进制文件中读取 block 并使用 Python 或 Perl 解包提取结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11253791/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com