Converting number into 32 bits in python

-2

I have 32 bit numbers A=0x0000000A and B=0X00000005.

I get A xor B by A^B and it gives 0b1111.

I rotated this and got D=0b111100000 but I want this to be 32 bit number not just for printing but I need MSB bits even though there are 0 in this case for further manipulation.

python
bit-manipulation
32-bit
asked on Stack Overflow Sep 15, 2015 by Aashish sharma Sharma • edited Sep 15, 2015 by Leb

3 Answers

2

Most high-level languages don't have ROR/ROL operators. There are two ways to deal with this: one is to add an external library like ctypes or https://github.com/scott-griffiths/bitstring, that have native support for rotate or bitslice support for integers (which is pretty easy to add).

One thing to keep in mind is that Python is 'infinite' precision - those MSBs are always 0 for positive numbers, 1 for negative numbers; python stores as many digits as it needs to hold up to the highest magnitude difference from the default. This is one reason you see weird notation in python like ~(0x3) is shown as -0x4, which is equivalent in two's complement notation, rather than the equivalent positive value, but -0x4 is always true, even if you AND it against a 5000 bit number, it will just mask off the bottom two bits.

Or, you can just do yourself, the way we all used to, and how the hardware actually does it:

def rotate_left(number, rotatebits, numbits=32):
    newnumber = (number << rotatebits) & ~((1<<numbits)-1)       
    newnumber |= (number & ~((1<<rotatebits)-1)) << rotatebits
    return newnumber
answered on Stack Overflow Sep 15, 2015 by Corley Brigman
1

To get the binary of an integer you could use bin().

Just an short example:

>>> i = 333333
>>> print (i)
333333
>>> print (bin(i))
0b1010001011000010101
>>> 
answered on Stack Overflow Sep 15, 2015 by frlan • edited Sep 15, 2015 by frlan
1
bin(i)[2:].zfill(32)

I guess does what you want.

I think your bigger problem here is that you are misunderstanding the difference between a number and its representation

12 ^ 18  #would xor the values
56 & 11  # and the values 

if you need actual 32bit signed integers you can use numpy

a =numpy.array(range(100),dtype=np.int32)
answered on Stack Overflow Sep 15, 2015 by Joran Beasley • edited Sep 16, 2015 by Joran Beasley

User contributions licensed under CC BY-SA 3.0