scott-griffiths / bitstring

A Python module to help you manage your bits
https://bitstring.readthedocs.io/en/stable/index.html
MIT License
405 stars 68 forks source link

Switching bit order? #218

Closed IamMusavaRibica closed 3 years ago

IamMusavaRibica commented 3 years ago

Say we have this bit stream: 00000111 00000101 10010000 00011001 (spaces for easier reading) Is it possible to change the bit order / endianness of each byte in it? So for example, first one becomes 11100000, second 10100000 etc. I need the least significant bit read first I know its possible for bytes, but what about bits? Thanks in advance

scott-griffiths commented 3 years ago

The easiest way to do this is to reverse all the bits, then reverse the bytes:

    s = bitstring.BitArray('0b00000111 00000101 10010000 00011001')
    s.reverse()
    s.byteswap()

>>> s.bin
'11100000101000000000100110011000'

For large amounts of data this won't be very efficient though.

IamMusavaRibica commented 3 years ago

Thank you! I won't handle large amounts of data though, maximum of 16 bytes at once so this will be much useful!

pon, 3. svi 2021. u 13:44 Scott Griffiths @.***> napisao je:

The easiest way to do this is to reverse all the bits, then reverse the bytes:

s = bitstring.BitArray('0b00000111 00000101 10010000 00011001')
s.reverse()
s.byteswap()

s.bin '11100000101000000000100110011000'

For large amounts of data this won't be very efficient though.

— You are receiving this because you authored the thread. Reply to this email directly, view it on GitHub https://github.com/scott-griffiths/bitstring/issues/218#issuecomment-831206706, or unsubscribe https://github.com/notifications/unsubscribe-auth/APWMGTRCATGIYAVCD4DXI2LTL2EAJANCNFSM425GPNBQ .