简体   繁体   中英

python - cut a x-bit binary number to a byte (8bit)

I am using python 2.7. I need to truncate a binary number from a x-bits to 8 bits (byte) i will write an example of what i would like to do to make it clear and also because stackexchange doesn't leave me write my question for some reason, example:

0b1010101010100101 -> 0b10100101

i tried this workaround: converting it to string and then cutting it as a sub-string, but i didn't manage to make it working

str_cs = str(bin(cs))
str_cs = str_cs[to_cut:]

but i am facing many problem to convert it back to a binary number... how would you truncate it?

Simply use a bitwise & with a byte of all 1 s:

cs = cs & 0b11111111
# or, if you're feeling daring:
cs &= 0b11111111

Solution of Phydeaux much better but I was doing :

>>> cs=0b1010101010100101
>>> cs=int(bin(cs)[-8:], 2)
>>> bin(cs)
'0b10100101'

Based on what you were trying with str

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM