简体   繁体   English

python - 将x位二进制数切换为一个字节(8位)

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

I am using python 2.7. 我正在使用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: 我需要将一个二进制数从一个x位截断到8位(字节)我将写一个我想做的事情的例子,以便清楚,并且因为stackexchange不会因为某些原因让我写出我的问题,例:

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: 只需使用按位&所有1 s的字节:

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

Solution of Phydeaux much better but I was doing : Phydeaux的解决方案要好得多,但我在做:

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

Based on what you were trying with str 基于你在str上尝试的内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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