Work with bit streams

I have a base64 encoded bit that I want to work with. After decoding with, base64.b64decodeI get a byte object (Py3k btw) containing the decoded code. The problem is that I would like to work on this object with bit operations such as shift, wise bit and, etc., but this is not possible, since it is a sequence of bytes.

Is there a way to use binary operations on this decoded code?

+3
source share
3 answers

try using

list(bytestring)

Eg.

>>> bstring=b"Hello World"
>>> list( bstring)
[72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
>>> 

If you want one huge bit field, not all those octets

>>> from functools import reduce
>>> reduce(lambda x,y:(x<<8)+y,list(b"Hello World"))
87521618088882533792115812
>>> bin(_)
'0b100100001100101011011000110110001101111001000000101011101101111011100100110110001100100'
>>> 

You did not say how you consider the bit, perhaps they should be canceled.

>>> reduce(lambda x,y:(x<<8)+y,list(b"Hello World"[::-1]))
121404708493354166158910792
>>> bits=bin(_)[2:]

and insert the string in even bytes

>>> bits=bits.zfill(((len(bits)-1)//8+1)*8)
>>> bits
'0110010001101100011100100110111101010111001000000110111101101100011011000110010101001000'

6 int

>>> int(bits[:6],2)
25

4

>>> int(bits[6:10],2)
1
+4

bytes, bytearray:

mutable = bytearray(b"immutable")

mutable[0] = mutable[1] = 32

- , bitstring ( ). Python 3 - , , .

>>> s = bitstring.BitArray(bytes=b'your_bytes_object')
>>> s.hex
'0x796f75725f62797465735f6f626a656374'
>>> ten_bits = s[5:15]
>>> print(ten_bits, ten_bits.int)
0b0010110111 183
>>> print(ten_bits << 2)
0b1011011100
>>> print(s[0:6] & '0b110100')
0b010100
+2

Python 2.x, Construct. , .

, , Python 3.x. 2.x .

0

Source: https://habr.com/ru/post/1725002/


All Articles