decimal = int(input("Enter the Decimal value :"))
def d_b(decimal,binary):
# function to convert decimal to binary
binary = binary + str(decimal % 2)
if decimal > 1:
d_b(decimal//2,binary)
else :
print (binary)
return (binary)
print ("Decimal to Binary : ", d_b(decimal,binary = ''))
Output for input 34:
010001
Decimal to Binary : None
The function prints the answer but doesn't return it and then starts going back to function and starts deleting characters one by one from the string and finally returns none instead of the binary string.
Correct Code :
decimal = int(input("Enter the Decimal value :"))
def d_b(decimal,binary):
# function to convert decimal to binary
if decimal > 0:
binary = d_b(int(decimal)//2,binary)
binary = binary + str(decimal % 2)
return (binary)
print ("Decimal to Binary :",d_b(decimal,binary = ''))
Try this, your welcome:
def d_b(decimal,binary):
# function to convert decimal to binary
binary = binary + str(decimal % 2)
if decimal > 1:
binary = d_b(int(decimal/2), binary) # <-- this is the line you should change
return binary
Or even shorter with the ternary operator:
return decimal > 1 ? d_b(int(decimal/2), binary): binary
Related
sample input:
B15
sample output:
B15 in binary = 1011000010101
I've tried
a = input()
print(bin(a))
The hexadecimal number 0xB15 = 2837 has the binary representation 0b101100010101. So if your input is a hexadecimal number, you need to tell Python to convert the string "B15" which comes out of input() into the hexadecimal number 0xB15, also known as the decimal number 2837, before you can convert it into binary for output.
BASE = 16
a = int(input(), BASE)
print(bin(a)[2:]) # Cut of the first two characters '0b'
in attempt to make simple code to convert a hex string to base64:
my thought was: hex -> integer -> binary -> base64
so i wrote this little code:
import string
def bit(integer):
# To binary
return int(bin(integer))[2:]
#Hex multiply by 16 depending on position: 0xAB = A*(16**2) + B(16**1) = #10*16**2 + 11*16**1
#0x3a2f
#3*(16**2) + 7*(16**1) + 5
def removeletter(list):
#"abcdef" = "10 11 12 13 14 15"
for i, letter in enumerate(list):
if letter in hextable.keys():
list[i] = hextable[letter]
return list
def todecimal(h):
power = 0
l = [num for num in str(h)] #['3', 'a', '2', 'f']
l = removeletter(l)
l.reverse() #['f', '2', 'a', '3']
for i, n in enumerate(l):
number = int(n)
l[i] = number*(16**power)
power += 1
l.reverse()
return sum(l)
lowers = string.ascii_lowercase
hextable = {}
for number, letter in enumerate(lowers[:6]):
hextable[letter] = number + 10
in this little challenge i am doing, it says:
The string:
49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d
Should produce:
SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t
ok,
print(bit(todecimal('49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d')))
this should get the binary of the hex string, which if I put through a binary to base64 converter, should return SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t. or so i thought.
└─$ python3 hextobase64.py
10010010010011101101101001000000110101101101001011011000110110001101001011011100110011100100000011110010110111101110101011100100010000001100010011100100110000101101001011011100010000001101100011010010110101101100101001000000110000100100000011100000110111101101001011100110110111101101110011011110111010101110011001000000110110101110101011100110110100001110010011011110110111101101101
after checking using a hex to binary converter, i can see that the binary is correct.
now, if if i put this through a binary to base64 converter, it should return SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t, right?
the thing is, this binary to base64 converter gave me kk7aQNbS2NjS3M5A8t7q5EDE5MLS3EDY0tbKQMJA4N7S5t7c3urmQNrq5tDk3t7a which is odd to me. so I must be doing something wrong. from my understanding, hexadecimal can be represented in binary, and so can base64. base64 takes the binary and groups the binary by 6 digits to produce its own representation. so obviously if I have the binary, it should be interchangeable, but something is wrong.
what am i doing wrong?
Can anyone please give me instruction how to write the program using this algorithm?
To convert binary integer to decimal, start from the left. Take your current total, multiply it by two and add the current digit. Continue until there are no more digits left.
First need to input the binary number as a string then select one by one digits of binary number
num=input("Enter the binary integer Number: ")
num=str(num)
decimal=''
rem=0
i=0
i=int(i)
dig=num[i]
dig=int(dig)
rem=(rem*2)+dig
i=i+1
dig=num[i]
dig=int(dig)
rem=(rem*2)+dig
i=i+1
dig=num[i]
dig=int(dig)
rem=(rem*2)+dig
i=i+1
dig=num[i]
dig=int(dig)
rem=(rem*2)+dig
i=i+1
decimal=int(rem)
print(decimal)
This code only calculate 4 digits of binary numbers. How can i add a while loop in this code?
Yes, you can put that in a loop:
binary = input("Enter the binary integer Number: ")
decimal = 0
for dig in binary:
decimal = decimal*2 + int(dig)
print(decimal)
Note that in Python 3, input already returns a string type value, so you don't need to convert it with str().
You can use the int() function:
binary_string = input('Please input a binary number: ')
print(int(binary_string, 2))
A one liner, just because it is possible:
print(int(input('Please input a binary number: '), 2))
But if you really want to do this with a loop, you can do:
binary_string = input('Please input a binary number: ')
result = 0
multiplier = 1
for digit in binary_string[::-1]:
result += int(digit) * multiplier
multiplier *= 2
print(result)
I am currently writing a Python 3 program to convert decimal to binary among other things for a Uni assignment.
I've nailed everything except for this in the first stage (decimal to binary).
dec = int(input("Enter a number: "))
while dec > 0 or dec == 0:
if dec > 0:
rem = dec % 2
dec = dec // 2
print(rem, end = "")
The output gives the binary number correctly, however it is in reverse.
Can you please tell me how to reverse the output or reverse the conversion process or something to correct the output?
EDIT: I cannot use in-built functions such as bin(dec), etc.
Thanks!
The above code is not decimal to binary, instead it is an example of dividend/reminder. You can do that as follows:
dec, rem = divmod(dec, 2)
If you still want to convert decimal to binary do -
bin(dec)
Based on the comment, would this help?
def dec2bin(d):
s = ''
while d>0:
d,r = divmod(d, 2)
s += str(r)
return s[::-1]
>>> dec2bin(6)
'110'
python program to convert the given binary to decimal, octal and hexadecimal number and vice versa.
conversions of all bases with each other.
x = int(input("press 1 for dec to oct,bin,hex \n press 2 for bin to dec,hex,oct \n press 3 for oct to bin,hex,dec \n press 4 for hex to bin,dec,oct \n"))
if x is 1:
decimal =int(input('Enter the decimal number: '))
print(bin(decimal),"in binary.")
print(oct(decimal),"in octal.")
print(hex(decimal),"in hexadecimal.")
if x is 2:
binary = input("Enter number in Binary Format: ");
decimal = int(binary, 2);
print(binary,"in Decimal =",decimal);
print(binary,"in Hexadecimal =",hex(decimal));
print(binary,"in octal =",oct(decimal));
if x is 3:
octal = input("Enter number in Octal Format: ");
decimal = int(octal, 8);
print(octal,"in Decimal =",decimal);
print(octal,"in Hexadecimal =",hex(decimal));
print(octal,"in Binary =",bin(decimal));
if x is 4:
hex = input("Enter number in hexa-decimal Format: ");
decimal = int(hex, 16);
print(hex,"in Decimal =",decimal);
print(hex,"in octal =",oct(decimal));
print(hex,"in Binary =",bin(decimal));
how to convert decimal to binary by using repeated division in python?
i know i have to use a while loop, and use modulus sign and others {%} and {//} to do this...but i need some kind of example for me to understand how its done so i can understand completely.
CORRECT ME, if I'm wrong:
number = int(input("Enter a numberto convert into binary: "))
result = ""
while number != 0:
remainder = number % 2 # gives the exact remainder
times = number // 2
result = str(remainder) + result
print("The binary representation is", result)
break
Thank You
Making a "break" without any condition, makes the loop useless, so the code only executes once no matter what.
-
If you don't need to keep the original number, you can change "number" as you go.
If you do need to keep the original number, you can make a different variable like "times".
You seem to have mixed these two scenarios together.
-
If you want to print all the steps, the print will be inside the loop so it prints multiple times.
If you only want to print the final result, then the print goes outside the loop.
while number != 0:
remainder = number % 2 # gives the exact remainder
number = number // 2
result = str(remainder) + result
print("The binary representation is", result)
-
The concatenation line:
Putting the print inside the loop might help you see how it works.
we can make an example:
the value in result might be "11010" (a string, with quotes)
the value in remainder might be 0 (an integer, no quotes)
str(remainder) turns the remainder into a string = "0" instead of 0
So when we look at the assignment statement:
result = str(remainder) + result
The right side of the assignment operator = is evaulated first.
The right side of the = is
str(remainder) + result
which, as we went over above has the values:
"0" + "11010"
This is string concatenation. It just puts one string on the end of the other one. The result is:
"0 11010"
"011010"
That is the value evaluated on the right side of the assignment statement.
result = "011010"
Now that is the value of result.
B_Number = 0
cnt = 0
while (N != 0):
rem = N % 2
c = pow(10, cnt)
B_Number += rem * c
N //= 2
# Count used to store exponent value
cnt += 1
return B_Number