convert a number or string to binary number in python? - python-3.x

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'

Related

The conversion of a hex value of length 16 isn't correct

I have a hex value of 16 digits (i.e., length 16) that I want to convert to binary as the following:
n = '5851F42D00000000' # length = 16
bin_ = bin(int(n, 16))[2:]
print(len(bin_))
I get here 63 but I expect the length of the resulted binary to be 64. Am I doing something wrong here?
Thank you
bin doesn't give you leading zeroes, because it has no way of knowing how many leading zeroes you would want. You can get the desired behaviour using string formatting:
>>> n = '5851F42D00000000'
>>> '{:064b}'.format(int(n, 16))
'0101100001010001111101000010110100000000000000000000000000000000'
>>> len(_)
64
The format string {:064b} formats an integer in binary, with leading zeroes up to length 64.
This number in binary has a leading zero:
>>> f'{int(n, 16):064b}'
'0101100001010001111101000010110100000000000000000000000000000000'
bin will return the shortest possible representation, not including leading zeros:
>>> bin(int(n, 16))
'0b101100001010001111101000010110100000000000000000000000000000000'
^ there's technically a zero before that

multiple float input() with for loop value

I am trying get floating point number from user input with for loop in python 3.6.7:
for _ in range(int(input())):
foo = float(input())
Input:
1
12.3
No error, But when it is more than one value Error shows up:
for _ in range(int(input())):
foo = float(input())
Input:
2
2.5 3.1
ValueError: Could not convert string to float: '2.5 3.1'
any thoughts? thanks in advance.
When you input something and press Enter, input treats that data as a single string. So, 3.141<hit Enter> is a single string "3.141", and it can be converted to a floating-point number with float.
However, 3.141 5926<hit Enter here> is a single string "3.141 5926". Is that a representation of a single (floating-point) number? It's not (there are two numbers), so float can't convert that to a single number because of the space.
If you want to treat these numbers separated by a space as individual numbers, split the string and then convert each number:
data = input().split() # gives ['3.141', '5926']
for x in data:
print(float(x)) # converts each string to a number

Convert binary integer to decimal using bellow algorithm

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)

Binary conversion Python output issues

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 a double array to character string

hello i have entered some text and convert it to the binary values.these binary values get stored in a array of data type double. Now i want to get the char array from that array containing binary values.
text2='hello how are u';
text3=double(text2);
nValues = numel(text3);
B=8;
bit_stream = zeros(1,nValues*B);
% eight bit for binary representation of each character.
for iBit = 1:B %# Loop over the bits
bit_stream(iBit:B:end) = bitget(text3,B-iBit+1); %# Get the bit values
end
bitstream=bit_stream;
how to perform vice-versa..
text2_recovered = char( 2.^(7:-1:0) * reshape(bit_stream, 8, []) );
Explanation:
Arrange bits in groups of 8 (reshape(...,8,[]));
Convert each group to a byte value (2.^(7:-1:0)*...) ;
Convert those bytes to characters (char).

Resources