top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration
Print Preview

how to get binary equivalent of a decimal number in python

+1 vote

I need to get 32 bit binary equivalent of a decimal and need to change the 0's to 1's and 1's to 0's

For Example
if the input is 2 
Output should be:
the 32bit equivalent of 2 :0000 0000 0000 0000 0000 0000 0000 0010
and the 1's compliment is:1111 1111 1111 1111 1111 1111 1111 1101

is there any pre-defined function to get the above results in python??

posted May 23, 2013 by anonymous

Share this question
Facebook Share Button Twitter Share Button Google+ Share Button LinkedIn Share Button Multiple Social Share Button

1 Answer

0 votes

I'm curious as to the intent of the assignment. Are you supposed to be learning about base conversion, about ones and twos complement, or about Python?

Assuming the intent is to learn about Python, the built-in function bin() will take a Python integer (which is not decimal) and convert it to a str. At that point, you can manipulate the string any way you like.

x = 45
print bin(45)

Perhaps you want to start by stripping off the leading '0b' using a slice. Then you want to pad it to 32 columns by prepending some number of zeroes. Then you want to insert some spaces at regular intervals.

Presumably doing the ones-complement operation on that string is then pretty easy for you.

answer May 23, 2013 by anonymous
Similar Questions
+1 vote

I have about 500 search queries, and about 52000 files in which I have to find all matches for each of the 500 queries.

How should I approach this? Seems like the straightforward way to do it would be to loop through each of the files and go line by line comparing all the terms to the query, but this seems like it would take too long.

Can someone give me a suggestion as to how to minimize the search time?

+2 votes

I am trying to test measure some IO execution in milliseconds , but bit confuse about best method achive that under windows 7. I am using following code but not sure if its best or correct way since i have two different results, which one should i take as results and which is best way. Please advice

code exec results 
100000000 loops, best of 3: 0.00925 usec per loop

run code
 import timeit ,time
 import datetime
 import os

 def main():    
 if __name__ == '__main__':    
 t = timeit.Timer('main()')    
 print (t.timeit(1))
+3 votes

I am trying to count the number of files in a folder with python script but not getting the appropriate script. In which I can change the path and can find out the count of other folder files.

It doesn't matter for me how long the script is but need the clear script and it would be better if you can explain it also.

Useful Links with Similar Problem
Contact Us
+91 9880187415
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Karnataka INDIA.