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?
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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments