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?

Steff
  • 31
  • 1
  • 5
  • Do you have to write the function as an exercise? Otherwise use `bin`. – juanchopanza Nov 22 '15 at 22:13
  • @juanchopanza yup, I have to write a function unfortunately – Steff Nov 22 '15 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. – DisappointedByUnaccountableMod Nov 22 '15 at 22:58
  • @barny I thought that was what I was doing with "dec % 2". Could you give me another hint? – Steff Nov 22 '15 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. – DisappointedByUnaccountableMod Nov 22 '15 at 23:16
  • Possible duplicate of [Convert decimal to binary in python](http://stackoverflow.com/questions/3528146/convert-decimal-to-binary-in-python) – TessellatingHeckler Nov 22 '15 at 23:58
  • I hope you worked out your own answer. SO isn't supposed to be a coding service, and as you stated you have to write this yourself, I hope you tried. I believe academic institutions have alarmingly effective plagiarism detectors built into their student course work management systems these days. I assume these include looking on SO for related questions/answers :-o – DisappointedByUnaccountableMod Nov 23 '15 at 00:34
  • @barny Actually we're encouraged to seek out help on SO if we have questions or need help coding. I did try a number of things before posting here. I wasn't trying to have someone code this for me, I was looking for hints and explanations (that I may not have found already via google)... – Steff Nov 23 '15 at 22:02
  • My point was - someone providing working code to you may 'help' you get some working code for your exercise, but if the point of the exercise is for you to learn how to write code to solve the problem, by taking the 'help' you will have likely avoided doing a lot of the learning. Come here with a Minimal Complete Verifiable Example http://stackoverflow.com/help/mcve which your code above *isn't* because e.g. you aren't showing a call to your dec2bin function. – DisappointedByUnaccountableMod Nov 24 '15 at 10:46
  • @barny Alright, got it - I'll do better next time! Thanks :) – Steff Nov 24 '15 at 14:38

5 Answers5

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.

Falko
  • 17,076
  • 13
  • 60
  • 105
  • Ok, since you're supposed to write the function yourself, this solution won't help much. But I'll leave it here for reference. – Falko Nov 22 '15 at 22:19
  • It's definitely nice to see something work haha. Any suggestions regarding the function? – Steff Nov 22 '15 at 22:23
1

The following will work:

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

You can test it like this:

print dec2bin("11")
Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
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.

Pynchia
  • 10,996
  • 5
  • 34
  • 43
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
  • 17,076
  • 13
  • 60
  • 105
Marichyasana
  • 2,966
  • 1
  • 19
  • 20
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
CopyPasteIt
  • 532
  • 1
  • 8
  • 22