2

I'm trying to get a function to take a string dec, representing a decimal number, for example "11" and I want said function to return a string, which contains the corresponding binary format, in this case "1011". So this is what I have so far:

def dec2bin(dec):
 dec = str("11")
 if dec > 1:
 binary(dec//2)
 return (dec % 2,end = "")

I'm very new to Python, so I'm not sure how to turn a number into a string (using str()) in the first place and how to make it return the corresponding binary value. Can anyone point me in the right direction?

asked Nov 22, 2015 at 22:11
10
  • Do you have to write the function as an exercise? Otherwise use bin. Commented Nov 22, 2015 at 22:13
  • @juanchopanza yup, I have to write a function unfortunately Commented Nov 22, 2015 at 22:17
  • Think about how you represent a number using base 10, i.e. decimal - the rightmost digit (let's call this digit number 0) is the remainder after dividing by 10. The next digit (digit number 1) is the remainder after dividing (number/10) by 10. The next digit (digit number 2) is the remainder after dividing (number/100) by 10. Note that 100 is 10^2, i.e. 10^digitnumber. The nth digit is the remainder after dividing (number/10^digitnumber) by 10. Replace 10 by 2 and you will get binary representation. Now ignore the people providing answers for you and go code it. Commented Nov 22, 2015 at 22:58
  • @barny I thought that was what I was doing with "dec % 2". Could you give me another hint? Commented Nov 22, 2015 at 23:10
  • Yes, dec%2 is possibly part of the answer, as long as dec is an integer. In your code, is dec an integer? Try writing code to add 1 to it, does that work? BTW I'm not going to write the code for you - you have that job. Commented Nov 22, 2015 at 23:16

5 Answers 5

1

This should work:

def dec2bin(num):
 return bin(int(num))[2:]

int converts the string num into an integer. bin converts it into its binary representation (a string again). The [2:] drops the first two characters, which are only an indicator for the binary representation.

answered Nov 22, 2015 at 22:17
Sign up to request clarification or add additional context in comments.

2 Comments

Ok, since you're supposed to write the function yourself, this solution won't help much. But I'll leave it here for reference.
It's definitely nice to see something work haha. Any suggestions regarding the function?
1

The following will work:

def dec2bin(dec):
 return format(int(dec), "b")

You can test it like this:

print dec2bin("11")
answered Nov 22, 2015 at 22:20

Comments

0

Assuming you can use int to convert the string to an integer:

def dec2bin(snum):
 n = int(snum)
 bin_s = ['1' if (n >> b) & 1 else '0' for b in range(n.bit_length())]
 return ''.join(reversed(bin_s))

let's test it

>>> dec2bin('11')
'1011'

Basically, it scans the integer obtained from the string and checks every bit in it.

It shifts the number to the right and checks the least significant bit and-ing it with the value 1 (alternatively we could shift the mask to the left and leave the number unchanged).

The result of each bit-check is used to populate a list, which is then reversed and joined to form a string.

If using list comprehensions would make you look too cool to be true, use a for loop:

def dec2bin(snum):
 n = int(snum)
 bin_s = []
 for b in range(n.bit_length()):
 cur_bit = (n >> b) & 1
 sbit = chr(ord('0') + cur_bit)
 bin_s.append(sbit)
 return ''.join(reversed(bin_s))

Another solution, in case you can use python's builtin format function, would be:

def dec2bin(snum):
 return format(int(snum),"b")

Further note to clarify the algorithm (the main assumption is that we are only talking about unsigned integers):

Computers use binary representation of data (i.e. bits, zero and ones). Put one after the other, from right to left, they form a number in ascending powers of two, just like decimal digits do.

For example the number thirteen (13 is its representation in base ten: 1*10^1+3*10^0) is written as 1101 in binary (1*2^3+1*2^2+0*2^1+1*2^0) and stored in memory as bits within bytes (8-bits).

The LSB (Least Significant Bit) is the least powerful bit (binary digit), i.e. the rightmost one in 1101, because it weighs the least in terms of power of two.

Python allows a variable size for integers, that is why I use the bit_length method to find out how many bits are necessary to store that number. Other languages (e.g. C) allocate a predefined size to numbers, normally the same (or less) as the width of the registers the CPU provides.

answered Nov 22, 2015 at 22:19

9 Comments

What does the "b" specify exactly?
b stands for binary, of course. Please see the official docs for more info on the format spec
ah okay got it - Thank you!
@Tom Karzes Is there a way, which doesn't use format or "b"? I'd like to use something along the lines of the if statement I tried...
ohhhh, this helped a lot! :)
|
0

Here is a function that also allows you to choose the number of digits in the output.

def int2bin(n, count=24):
 """returns the binary of integer n, using count number of digits"""
 return "".join([str((n >> y) & 1) for y in range(count-1, -1, -1)]) 

It normally takes an int:

print int2bin(44) 
'000000000000000000101100' 

but you can use a string by converting it to int first:

print int2bin(int("44")) 
'000000000000000000101100'
Falko
18.2k14 gold badges65 silver badges119 bronze badges
answered Nov 23, 2015 at 0:01

Comments

0

The challenge here is to write a string processing algorithm that doesn't use any python math function. A specification for the following program can be found here.

Python Program

while True:
 indecimal_str = input('Enter (decimal) integer: ')
 if indecimal_str == '':
 raise SystemExit
 indecimal = list(indecimal_str)
 exbin = []
 print(indecimal, '<->', exbin)
 while True:
 if len(indecimal) == 0:
 print('Conversion', indecimal_str, '=', "".join(exbin))
 print()
 break
 carry_state = False 
 g = indecimal[len(indecimal)-1]
 if g in '02468':
 exbin.insert(0, '0')
 elif g in '13579':
 exbin.insert(0, '1')
 if g == '1': indecimal[len(indecimal)-1] = '0'
 elif g == '3': indecimal[len(indecimal)-1] = '2'
 elif g == '5': indecimal[len(indecimal)-1] = '4'
 elif g == '7': indecimal[len(indecimal)-1] = '6'
 else : indecimal[len(indecimal)-1] = '8' 
 else:
 print('Input not valid')
 raise SystemError
 for i in range(0,len(indecimal)):
 if carry_state == False:
 if indecimal[i] in '13579':
 carry_state = True 
 if indecimal[i] in '01':
 indecimal[i] = '0'
 elif indecimal[i] in '23':
 indecimal[i] = '1'
 elif indecimal[i] in '45':
 indecimal[i] = '2'
 elif indecimal[i] in '67':
 indecimal[i] = '3'
 elif indecimal[i] in '89':
 indecimal[i] = '4'
 else:
 print('Input not valid')
 raise SystemError
 else: # carry_state == True
 if indecimal[i] in '02468':
 carry_state = False
 if indecimal[i] in '01':
 indecimal[i] = '5'
 elif indecimal[i] in '23':
 indecimal[i] = '6'
 elif indecimal[i] in '45':
 indecimal[i] = '7'
 elif indecimal[i] in '67':
 indecimal[i] = '8'
 elif indecimal[i] in '89':
 indecimal[i] = '9'
 else:
 print('Input not valid')
 raise SystemError
 if indecimal[0] == '0':
 indecimal.pop(0) 
 print(indecimal, '<->', exbin)

OUTPUT

Enter (decimal) integer: 8
['8'] <-> []
['4'] <-> ['0']
['2'] <-> ['0', '0']
['1'] <-> ['0', '0', '0']
[] <-> ['1', '0', '0', '0']
Conversion 8 = 1000
Enter (decimal) integer: 37
['3', '7'] <-> []
['1', '8'] <-> ['1']
['9'] <-> ['0', '1']
['4'] <-> ['1', '0', '1']
['2'] <-> ['0', '1', '0', '1']
['1'] <-> ['0', '0', '1', '0', '1']
[] <-> ['1', '0', '0', '1', '0', '1']
Conversion 37 = 100101
Enter (decimal) integer: 409
['4', '0', '9'] <-> []
['2', '0', '4'] <-> ['1']
['1', '0', '2'] <-> ['0', '1']
['5', '1'] <-> ['0', '0', '1']
['2', '5'] <-> ['1', '0', '0', '1']
['1', '2'] <-> ['1', '1', '0', '0', '1']
['6'] <-> ['0', '1', '1', '0', '0', '1']
['3'] <-> ['0', '0', '1', '1', '0', '0', '1']
['1'] <-> ['1', '0', '0', '1', '1', '0', '0', '1']
[] <-> ['1', '1', '0', '0', '1', '1', '0', '0', '1']
Conversion 409 = 110011001
answered Mar 15, 2020 at 14:00

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.