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));
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?
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
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)
This code produces one number after the other as it converts decimal to binary.
dec = int(input("Please enter number to convert to decimal: "))
while dec>0:
quoteint = dec/2
rem = dec%2
print (int(rem), end = " ")
dec = int(dec/2)
The output is the following.
1 0 0 1 0
Is there a way to reverse the output order?
Eg. 0 1 0 0 1
It may work if the individual numbers generated are joined to a string and the string is reversed, but I don't know how to go about doing that.
I think the following code will work.
result = []
dec = int(input("Please enter number to convert to decimal: "))
while dec>0:
quoteint = dec/2
rem = dec%2
result.append(rem)
dec = int(dec/2)
result = result[::-1]
print(' '.join(str(r) for r in result))