So leggere i byte - x.read(number_of_bytes)
, ma come posso leggere i bit in Python?Come leggere i bit da un file?
devo leggere solo 5 bit (non 8 bit [1 byte]) da un file binario
Tutte le idee o approccio?
So leggere i byte - x.read(number_of_bytes)
, ma come posso leggere i bit in Python?Come leggere i bit da un file?
devo leggere solo 5 bit (non 8 bit [1 byte]) da un file binario
Tutte le idee o approccio?
Python può solo leggere un byte alla volta. Dovresti leggere un intero byte, quindi estrarre semplicemente il valore desiderato da quel byte, ad es.
b = x.read(1)
firstfivebits = b >> 3
O se si voleva i 5 bit meno significativi, piuttosto che i 5 bit più significativi:
b = x.read(1)
lastfivebits = b & 0b11111
Alcune altre utili informazioni manipolazione dei bit può essere trovato qui: http://wiki.python.org/moin/BitManipulation
quando la mia reputazione sale a 15, ti darò il pollice in su! (Sono nuovo qui) quindi, se faccio questo: b = x.read (1) firstfivebits = b >> 3 Prendo i primi 5 bit ... perché non firstfivebits = b >> 5? Voglio dire ... perché b >> 3? –
@HugoMedina se non sai perché 'firstfivebits = b >> 3 'sei sicuro che dovresti essere fiddlin' con bit? (Potresti diventare cieco o qualcosa del genere). –
ora ho capito, dal momento che 1 byte = 8 bit applicheremo l'operatore di spostamento a destra 3 (come l'eliminazione di quei 3 bit meno significativi) quindi otterremo i restanti 5 bit nel byte –
Come il stati di risposta accettati, standard I/O Python può solo leggere e scrivere interi byte alla volta. Tuttavia è possibile simulare un tale flusso di bit utilizzando questa ricetta per Bitwise I/O.
Aggiornamento:
Dal momento del sito codice Rosetta GNU license permette di copiare pari pari, ecco la versione di Python del bit-stream di I/O nella sua interezza:
Aggiornamento 2:
Dopo aver modificato la versione Python del codice Rosetta per funzionare invariata in entrambi Python 2 & 3, ho incorporato le modifiche in questa risposta.
class BitWriter(object):
def __init__(self, f):
self.accumulator = 0
self.bcount = 0
self.out = f
def __del__(self):
try:
self.flush()
except ValueError: # I/O operation on closed file
pass
def _writebit(self, bit):
if self.bcount == 8:
self.flush()
if bit > 0:
self.accumulator |= 1 << 7-self.bcount
self.bcount += 1
def writebits(self, bits, n):
while n > 0:
self._writebit(bits & 1 << n-1)
n -= 1
def flush(self):
self.out.write(bytearray([self.accumulator]))
self.accumulator = 0
self.bcount = 0
class BitReader(object):
def __init__(self, f):
self.input = f
self.accumulator = 0
self.bcount = 0
self.read = 0
def _readbit(self):
if not self.bcount:
a = self.input.read(1)
if a:
self.accumulator = ord(a)
self.bcount = 8
self.read = len(a)
rv = (self.accumulator & (1 << self.bcount-1)) >> self.bcount-1
self.bcount -= 1
return rv
def readbits(self, n):
v = 0
while n > 0:
v = (v << 1) | self._readbit()
n -= 1
return v
if __name__ == '__main__':
import os
import sys
# determine module name from this file's name and import it
module_name = os.path.splitext(os.path.basename(__file__))[0]
bitio = __import__(module_name)
with open('bitio_test.dat', 'wb') as outfile:
writer = bitio.BitWriter(outfile)
chars = '12345abcde'
for ch in chars:
writer.writebits(ord(ch), 7)
with open('bitio_test.dat', 'rb') as infile:
reader = bitio.BitReader(infile)
chars = []
while True:
x = reader.readbits(7)
if reader.read == 0:
break
chars.append(chr(x))
print(''.join(chars))
Un altro esempio di utilizzo che mostra come "crunch" un flusso di byte ASCII 8-bit scartando il più significativo bit "non utilizzati" ... e leggerlo di nuovo.
import sys
import bitio
o = bitio.BitWriter(sys.stdout)
c = sys.stdin.read(1)
while len(c) > 0:
o.writebits(ord(c), 7)
c = sys.stdin.read(1)
... e di "decrunch" lo stesso flusso:
import sys
import bitio
r = bitio.BitReader(sys.stdin)
while True:
x = r.readbits(7)
if not r.read: # nothing read
break
sys.stdout.write(chr(x))
Sono quei bit consecutivi? In tal caso, i cinque bit più significativi o i cinque bit meno significativi nel byte? –