2

For example, if we take 1 and transform it to unsigned 32-bits, it will be 00000000000000000000000000000001

How could you achieve this in python?

6
  • 2
    "{:032b}".format(1)? Commented Feb 13, 2015 at 8:35
  • Do you mean for display purposes, or do you need to convert a number into a type that is exactly 32 bits (for example., to pack it into a structure)? Commented Feb 13, 2015 at 8:35
  • 2
    What is the problem you are trying to solve? Please read about the X-Y problem. Commented Feb 13, 2015 at 8:36
  • I need to convert it to exactly 32 bits. Commented Feb 13, 2015 at 8:37
  • 4
    The solution you want is the conversion, but it's not the actual problem you're trying to solve. The problem you're trying to solve may have other solutions. And by not telling us why you want this conversion it will make it harder to give you a solution that works in a satisfactory (for you) way. Commented Feb 13, 2015 at 8:42

2 Answers 2

2
def convert(i):
    return int(bin(i+2**32)[-32:])

print convert(1)
print convert(32)
print convert(100)
print convert(-1)
print type(convert(1))

outputs

00000000000000000000000000000001
00000000000000000000000000100000
00000000000000000000000001100100
11111111111111111111111111111111
<type 'long'>
Sign up to request clarification or add additional context in comments.

Comments

0
bin(1)[2:].zfill(32)

'00000000000000000000000000000001'

1 Comment

This code creates a string representing 32 bits as "0" or "1"; it doesn't actually create a 32-bit integer value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.