By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,603 Members | 1,053 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,603 IT Pros & Developers. It's quick & easy.

Changing a decimal into a binary

P: 1
So yeah I'm kind of new to python and I wanted to know how to change a decimal to binary
Sep 11 '13 #1
Share this Question
Share on Google+
2 Replies

bvdet
Expert Mod 2.5K+
P: 2,851
The following function uses built-in function divmod and recursion:
Expand|Select|Wrap|Line Numbers
  1. def dec2bin(num):
  2.     ''' Convert a decimal integer to base 2.'''
  3.     if num == 0:
  4.         return ''
  5.     num, rem = divmod(num, 2)
  6.     return dec2bin(num)+str(rem)
Expand|Select|Wrap|Line Numbers
  1. >>> dec2bin(1234)
  2. '10011010010'
Sep 12 '13 #2

Expert 100+
P: 626
Python has a built in also
Expand|Select|Wrap|Line Numbers
  1.  print bin(1234)
  2. 0b10011010010 
Sep 12 '13 #3

Post your reply

Sign in to post your reply or Sign up for a free account.