Steff
Steff

Reputation: 31

Function that takes a string representing a decimal number and returns it in binary format

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?

Upvotes: 2

Views: 3809

Answers (5)

CopyPasteIt
CopyPasteIt

Reputation: 574

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

Upvotes: 0

Pynchia
Pynchia

Reputation: 11590

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.

Upvotes: 0

Marichyasana
Marichyasana

Reputation: 3154

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'

Upvotes: 0

Tom Karzes
Tom Karzes

Reputation: 24052

The following will work:

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

You can test it like this:

print dec2bin("11")

Upvotes: 1

Falko
Falko

Reputation: 17867

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.

Upvotes: 1

Related Questions