Perl:寻找和读取位,而不是字节 [英] Perl: seek to and read bits, not bytes

查看:141
本文介绍了Perl:寻找和读取位,而不是字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Perl中,我想查找文件的第n位(不是字节),然后读取下一个m位,返回为0和1的列表。



有没有简单的方法来做到这一点?

我意识到我可以编写一个包含常规查找和读取的子程序,但是想知道是否有更简单的解决方案。如果n是m的倍数,m是1,2,4,8,16,32中的一个,在一些平台上,你可以将整个文件读入一个字符串,并使用 vec 对于这一点。



(不可否认,这是一个相当有限的情况,但常见的情况。)

除此之外,只需要做数学;在伪代码中:

  discard = n%8; 
startbyte =(n-discard)/ 8
bits = m + discard
bytes = int((bits + 7)/ 8)
寻找开始字节
读取字节到字符串
@list = split //,解包$ {bits} b,字符串
拼接(@list,0,$ discard)
拼接(@list,$ m, @list)


In Perl, I want to seek to the nth bit (not byte) of a file and then read the next m bits, returned as a list of 0s and 1s.

Is there any easy way to do this?

I realize I can write a subroutine wrapping regular seek and read, but was wondering if there's a easier solution.

解决方案

If n is a multiple of m, and m is one of 1, 2, 4, 8, 16, 32, and on some platforms, 64, you can read the whole file into a string and use vec for this.

(Admittedly a fairly constraining case, but a common one.)

Barring that, you'll just have to do the math; in pseudo-code:

discard = n % 8;
startbyte = (n - discard) / 8
bits = m + discard
bytes = int( (bits + 7) / 8 )
seek to startbyte
read bytes into string
@list = split //, unpack "${bits}b", string
splice( @list, 0, $discard ) 
splice( @list, $m, @list )

这篇关于Perl:寻找和读取位,而不是字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆