简体   繁体   中英

Remove last digit from integer and put zero in python

I have the small code, which is converting the integer to 10 bit binary and forming it as integer:

a = 2251
binary = bin(int(a))[2:].zfill(15)
print binary

it will give result as:

100011001011

and after that I want to remove the last four digits from 100011001011 and put zeros instead of that, means my final answer should be:

100011000000

please suggest if any good ideas...

You can do this with some simple bit shifting :

>>> a = 2251
>>> a = (a >> 4) << 4  # <--
>>> print format(a, 'b')
100011000000

To demonstrate what's going on, imagine that a had the binary representation 1111 1111 :

a             == 11111111

a >> 4        == 00001111

(a >> 4) << 4 == 11110000

You can use a simple bitwise operation:

>>> a = 2251
>>> a = a & ~0b1111
>>> print format(a, 'b')
100011000000

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