Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove last digit from integer and put zero in python

Tags:

python

int

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...

like image 993
lkkkk Avatar asked Mar 27 '26 05:03

lkkkk


2 Answers

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 &gt&gt 4        == 00001111

(a &gt&gt 4) &lt&lt 4 == 11110000
like image 52
arshajii Avatar answered Mar 28 '26 19:03

arshajii


You can use a simple bitwise operation:

>>> a = 2251
>>> a = a & ~0b1111
>>> print format(a, 'b')
100011000000
like image 29
njzk2 Avatar answered Mar 28 '26 17:03

njzk2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!