Remove trailing zeros from binary result in python - python

We have a program that changes decimals to binary.
And the goal is to run the program, input a value, and outputs the value in binary.
The problem with my code is that it has trailing zeros when outputting the binary.
I need to achieve this without using external libraries like "math", so please stick to the built-in functions.
Current output:
Insert a value:
5
The number fits in 1 byte and is in binary:
00000101
Insert a value:
100
The number fits in 1 byte and is in binary:
01100100
Insert a value:
280
The number fits in 16 bits and is in binary:
0000000100011000
Expected output:
Insert a value:
5
The number fits in 1 byte and is in binary:
101
Insert a value:
100
The number fits in 1 byte and is in binary:
1100100
Insert a value:
280
The number fits in 16 bits and is in binary:
100011000
Current code:
def dec2bin(value, number_bits):
result = ''
while number_bits > 0:
bit_value = 2 ** (number_bits - 1)
if value >= bit_value:
result = result + '1'
value = value - bit_value
else:
result = result + '0'
number_bits = number_bits - 1
print(result)
input_ok = False
userinput = 0
while not input_ok:
print('Insert a value:')
userinput = int(input())
if userinput > 65535:
print('invalid, cant handle that big numbers, try again')
else:
input_ok = True
if userinput < 256:
print('The number fits in 1 byte and is in binary:')
dec2bin(userinput, 8)
else:
print('The number fits in 16 bits and is in binary:')
dec2bin(userinput, 16)

It easy with string formatting functions (see Pranav's comment). But perhaps in this case you want the algorithm to take care of it, and see treating it as a string is cheating.
def dec2bin(value, number_bits):
result = ''
starting = True
while number_bits > 0:
bit_value = 2 ** (number_bits - 1)
if value >= bit_value:
result = result + '1'
value = value - bit_value
starting = False
elif not starting:
result = result + '0'
number_bits = number_bits - 1
print(result)

Since you are storing the value as a string you can use
result.lstrip('0')
to remove the leading zeros from your answer.

Related

My binary conversion app only goes up to 5 binary digits, how do I write the code to make it limitless without having to write all the repetitive code

Is there any way I can make the limitation to the whole number you can convert to binary endless without having to write endless repetitive code for each stage of the whole number to binary conversion.
#this is my first attempt at creating a integer to binary converter
#currently only works with 5 digit binary output
integer = int(input('Please input a whole number you would like converted in to binary '))
remainder_1 = (integer) % 2
division_1 = (integer) // 2
#print(remainder_1)
#print(f"d1 {division_1}")
remainder_2 = (division_1 % 2)
division_2 = (division_1 // 2)
if division_2 == 0 and remainder_2 == 0:
remainder_2 = ('')
#print(remainder_2)
#print(f"d2 {division_2}")
remainder_3 = (division_2 % 2)
division_3 = (division_2 // 2)
if division_3 == 0 and remainder_3 ==0:
remainder_3 = ('')
#print(remainder_3)
#print(f"d3 {division_3}")
remainder_4 = (division_3 % 2)
division_4 = (division_3 // 2)
if division_4 == 0 and remainder_4 ==0:
remainder_4 = ('')
#print(remainder_4)
#print(f"d4 {division_4}")
remainder_5 = (division_4 % 2)
division_5 = (division_4 // 2)
if division_5 == 0 and remainder_5 ==0:
remainder_5 = ('')
#print(remainder_5)
#print(f"d5 {division_5}")
remainder_6 = (division_5 % 2)
division_6 = (division_5 // 2)
if division_6 == 0 and remainder_6 ==0:
remainder_6 = ('')
#print(remainder_6)
#print(f"d6 {division_6}")
Binary = (f'{remainder_6}{remainder_5}{remainder_4}{remainder_3}{remainder_2}{remainder_1}')
print (Binary)
also when printing the binary result is there a way to repeat printing of remainders in order of most significant number to least significant number without having to write it all out as I did above up until remainder 6, Of course depending on how large the whole number input is initially.
integer = int(input('Please input a whole number you would like converted in to binary '))
binary = ""
# while integer is greater than zero.
while integer > 0:
# get the remainder of integer divided by 2.
remainder = str(integer % 2)
# concat the remainder as prefix to the binary string
binary = remainder + binary
# integer division by 2 on the integer
integer = integer // 2
print(binary)
Output
Please input a whole number you would like converted in to binary 100
1100100

How can I retain zero in python for calculation?

So I supposed to verify if the input number is a UPC number or not. I have to allowed leading zeros and accounted it in the calculation.
Here is my current code, it works for all number except number has leading zeros:
Condition for UPC code valid:
Calculate the sum of multiplying odd digit index by 3 and even digit index by 1 of the input number.
Calculate the sum we just did modulo 10, get result digit.
If the resulting digit is between 1 and 9 then subtract result digit from 10. If the result digit is 0, add 0 to the to the base number to get the completed number.
def UPC_code(num):
sum_digit = 0
index = 0
num_temp = str(num)[:-1]
len_nt = len(num_temp)
for digit in num_temp:
if (index + 1) % 2 != 0: # If number position is odd
sum_digit += int(digit) * 3 # Sum = digit * 3
if index < len_nt: # Increase index till end
index += 1
elif (index + 1) % 2 == 0: # If number position is even
sum_digit += int(digit) * 1 # Sum = digit * 1
if index < len_nt:
index += 1
# print(sum_digit)
res_digit = sum_digit % 10
if 1 <= res_digit <= 9:
res_digit = 10 - res_digit # Res digit meet condition = 10 - res digit
if res_digit == num % 10:
return True
elif res_digit != num % 10:
return False
else:
print("Something went wrong")
# End UPC_code()
Call UPC_code()
import code_check.py as cc
num = str(input())
num_int = int(num)
if cc.UPC_code(num_int) is True and num_int != 0:
print(num, "valid UPC code.")
else:
print("Not valid")
Expected input:
042100005264
Expected output:
042100005264 valid UPC code
Actual output:
Not valid
it works for all number except number has leading zeros
As you have doubtless discovered, python does not allow you to write 0700. Historically that would have meant 0o700, or 448, which is likely not what you want anyhow...
In this case the solution is simple. If you need to handle numbers like 00007878979345, handle strings.
Thus refactor your code to take a string. As a bonus, int("000008") is 8, so when you need the number as a number you don't even have to do anything.

String concatenation in while loop not working

I'm trying to create a Python program that converts a decimal to binary.
Currently I have
working = int(input("Please select a non-negative decimal number to convert to binary. "))
x = ()
while working !=0:
remainder = working % 2
working = working // 2
if remainder == 0:
x = remainder + 0
print (working, x)
else:
x = remainder + 1
print (working, x)
print ("I believe your binary number is " ,x)
The while works on it's own if I print after that, but the if/else doesn't. I am trying to create a string that is added to with each successive division. Currently, if my starting int is 76, my output is
38 0
38 0
19 0
19 0
9 2
4 2
2 0
2 0
1 0
1 0
0 2
I am trying to get my output to instead be
38 0
19 00
9 100
4 1100
2 01100
1 001100
0 1001100
This is my first attempt at string concatenation and I've tried a few variations of the above code to similar results.
There are a few issues with the code you’ve provided:
x starts with a value of (), and in any case, rather than concatenating strings to it, you’re adding numbers within the loop.
You’re trying to append the numbers rather than prepend, so the result would be reversed if it worked.
Your second print is not inside the conditional, so the output is duplicated.
What you need to do is initialize x with an empty string and then prepend strings to it:
working = int(input("Please enter a non-negative decimal number to convert to binary: "))
x = ""
while working != 0:
remainder = working % 2
working = working // 2
if remainder == 0:
x = "0" + x
else:
x = "1" + x
print (working, x)
print ("I believe your binary number is", x)
Output:
λ python convert-to-binary.py
Please enter a non-negative decimal number to convert to binary: 76
38 0
19 00
9 100
4 1100
2 01100
1 001100
0 1001100
I believe your binary number is 1001100
The problem is that you are not working with strings. You are first creating an empty tuple for x, and then overwriting that with an integer value later.
To do what you are attempting, you need to treat x as a string, and append the string literals '0' and '1' to it.
Try this instead:
working = int(input("Please select a non-negative decimal number to convert to binary. "))
x = ''
while working !=0:
remainder = working % 2
working = working // 2
if remainder == 0:
x += '0'
print (working, x)
else:
x += '1'
print (working, x)
print ("I believe your binary number is " , x[::-1])
Note how x is initially declared as an empty string '' instead of the empty tuple (). This makes it so that when you use the += operator later to append 0 or 1 to it, that it is treated as string concatenation instead of addition.
It should be
working = int(input("Please select a non-negative decimal number to convert to binary. "))
x = ""
while working !=0:
remainder = working % 2
working = working // 2
if remainder == 0:
x = x + str(remainder)
print (working, x)
else:
x = x + str(remainder)
print (working, x)
print ("I believe your binary number is " ,x[::-1])
Change your code to below:
if remainder == 0:
x = str(remainder) + '0'
print (working, x)
else:
x = str(remainder) + '1'
print (working, x)
in your code, python interprets as an int you have to cast it to string.
another way is using built-in function bin(working), directly converts from number to binary value.

Python program explanation: Decimal to hex

Can someone explain to me how this works? I keep looking at it but I just don't understand. It seems to work just fine but to the life of me this makes no sense. Somebody please help.
# Convert a decimal to a hex as a string
def decimalToHex(decimalValue):
hex = ""
while decimalValue != 0:
hexValue = decimalValue % 16
hex = toHexChar(hexValue) + hex
decimalValue = decimalValue // 16
return hex
# Convert an integer to a single hex digit in a character
def toHexChar(hexValue):
if 0 <= hexValue <= 9:
return chr(hexValue + ord('0'))
else: # 10 <= hexValue <= 15
return chr(hexValue - 10 + ord('A'))
def main():
# Prompt the user to enter a decimal integer
decimalValue = eval(input("Enter a decimal number: "))
print("The hex number for decimal",
decimalValue, "is", decimalToHex(decimalValue))
main() # Call the main function
Printing characters
Alright, im gonna try to explain it a bit. First, lets see the function that converts a number from 0-15 to 0123...ABCDEF:
def toHexChar(hexValue):
if 0 <= hexValue <= 9:
return chr(hexValue + ord('0'))
else: # 10 <= hexValue <= 15
return chr(hexValue - 10 + ord('A'))
You can see, its handling two cases: one, where the number 0-9 need to get converted into a text character from '0' to '9', another one where the number 10-16 need to get converted into a text character from 'A' to 'F'. It will return characters based on their ASCII-Code. For example, ord('A') returns 65.. chr() will convert an integer from 65 back to the ascii char 'A'.
Thats it about the print function. Now the loop:
Iterating number until all hex-chars are made
while decimalValue != 0:
This loop will run until not 16er chunk can be fetched
hexValue = decimalValue % 16
Normal modulo. It extracts a chunk from the decimal (hexValue will be 0-15)
hex = toHexChar(hexValue) + hex
Builds up a string. As HEX is standardtized to have bigger parts of the number on the left side, it is prepending the converted character.
decimalValue = decimalValue // 16
Preparing for the next loop: remove this 16er chunk by using a floordiv(a, b) (written as a // b).
Example
Lets understand how that works. Lets assume we want to convert the number 255 into a HexString. It will start by calling modulo 255 % 16 = 15. Then it will get converted toHexChar(15) = 'F'.
Next step is to remove that 16er chunk. If we would use normal division, we would get 255 / 16 = 15.9375. However, this would be rounded up because its above .5 after decimalpoint Causing a wrong behaviour (result would be 0x1FF).. Thats why we have to use a floordivsion which is floor(255/16) = 15 or shortly: 255 // 16 = 15.
I hope this explains it a bit better, especially why the // is needed.
I will have a go explaining using an example decimal number 11 to start with.
11 decimal is 0xB
11 modulo 16 is 11. Agreed? That means hexValue becomes the integer 11.
So the integer 11 gets passed to toHexChar.
so we have:
toHexChar(11)
11 is greater than 9, so the else path is called.
11 - 10 is of course 1.
The ascii value 'A' is 65 or 0x41, so ord('A') yields 65
1 + 65 = 66.
chr() function converts an integer value to an ASCII character. ascii 66 is 'B'. so toHexChar returns 'B'
Therefore, hex = 'B'
Now, decimalValue // 16, remember this is integer division, results in zero and hence we break out of the while loop and therefore decimalToHex(11) returns 'B'.
Example number 17.
17 modulo 16 = 1 - we have a string '1'
17 / 16 = 1 also. So we loop round one more time.
on the next iteration 1 % 16 yields 1, toHexChar returns '1' as a result.
hex = toHexChar(hexValue) + hex
will then mean that:
hex = toHexChar(1) + '1'
hex = '1' + '1'
results in "11"
Think it through with a few example numbers. Substituting as you go.
The basis of it is modulo 16 to get a remainder. The remainder cannot immediately be used because if the number is between 10 and 16 then you need to use the A-F characters, hence use of toHexChar function.
Then you divide by 16 and continue taking the remainder of what's left.

Using Python to convert integer to binary

I'm trying to convert integer to binary. This is my work.
I don't know how the make a list to show the binary.
num_str = input("Please give me a integer: ")
num_int = int(num_str)
while num_int > 0:
if num_int % 2 == 0:
num_int = int(num_int / 2)
num_remainder = 1
print("The remainder is:", 0)
continue
elif num_int % 2 == 1:
num_int = int(num_int / 2)
num_remainder = 1
print("The remainder is:", 1)
continue
How to make the remainder together?
Are you aware of the builtin bin function?
>>> bin(100)
'0b1100100'
>>> bin(1)
'0b1'
>>> bin(0)
'0b0'
You are on the right track, you just need to save the digits in a variable somewhere instead of just printing them to the screen:
num_str = input("Please give me a integer: ")
num_int = int(num_str)
num_bin_reversed = ''
while num_int > 0:
if num_int % 2 == 0:
num_int = int(num_int / 2)
num_remainder = 1
print("The remainder is:", 0)
num_bin_reversed += '0'
elif num_int % 2 == 1:
num_int = int(num_int / 2)
num_remainder = 1
print("The remainder is:", 1)
num_bin_reversed += '1'
num_bin = num_bin_reversed[::-1]
if int(num_str) > 0:
assert '0b' + num_bin == bin(int(num_str))
Now, try to fix it by making it work with negative numbers and 0 too!
#First off yes there is an easier way to convert i.e bin(int) but where is the fun in that
"""First we ask the user to input a number. In Python 3+ raw input is gone
so the variable integer_number will actually be a string"""
integer_number = input('Please input an integer') #get integer whole number off user
"""We could use int(input('Please input an integer')) but we don't want to overload
anyones brains so we show casting instead"""
'''Next we convert the string to an integer value (cast). Unless the user enters text
then the program will crash. You need to put your own error detection in'''
integer_number = int(integer_number)
"""initialise a variable name result and assign it nothing.
This so we can add to it later. You can't add things to a place that doesn't exist"""
result = ''
'''since we are creating an 8bit binary maximum possible number of 255
we set the for loop to 8 (dont forget that x starts at 0'''
for x in range(8):
#The variable in the for loop will increase by 1 each time
#Next we get the modulos of the integer_number and assign it to the variable r
r = integer_number % 2
#then we divide integer number by two and put the value back in integer_value
#we use // instead of / for int division els it will be converted to a float point variable
integer_number = integer_number//2
#Here we append the string value of r which is an integer to result
result += str(r)
#This then loops back to the for loop whilst x<8
#then we assign the reverse of result using [::-1] to result
result = result[::-1]
#print out the result
print(result)
You can store the remainders as digits in a string. Here is one possible function to convert from decimal to binary:
def dec2bin(d_num):
assert d_num >= 0, "cannot convert negative number to binary"
if d_num == 0:
return '0'
b_num = ""
while d_num > 0:
b_num = str(d_num%2) + b_num
d_num = d_num//2
return b_num
#This is the same code as the one above it's just without comments
#This program takes a number from the user and turns it into an 8bit binary string
integer_number = int(input('Please input an integer'))
result = ''
for x in range(8):
r = integer_number % 2
integer_number = integer_number//2
result += str(r)
result = result[::-1]
print(result)
here is a code that works in python 3.3.0 the converts binary to integer and integer to binary, JUST COPY AND PASTE!!!
def B2D():
decnum = int(input("Please enter a binary number"), 2)
print(decnum)
welcome()
def D2B():
integer_number = input('Please input an integer')
integer_number = int(integer_number)
result = ''
for x in range(8):
r = integer_number % 2
integer_number = integer_number//2
result += str(r)
result = result[::-1]
print(result)
welcome()
def welcome():
print("*********************************************************")
print ("Welcome to the binary converter program")
print ("What would you like to do?")
print ("Type 1 to convert from denary to binary")
print ("Type 2 to convert from binary to denary")
print ("Type 3 to exit out of this program")
choice = input("")
if choice == '1':
D2B()
elif choice == '2':
B2D()
elif choice == '3':
print("Goodbye")
exit
welcome()
I give thanks to nikpod. His code helped me give out my own answer.
Hope this helps.
# Define your functions here.
def int_to_reverse_binary(num):
string = ''
while num > 0:
string += str(num % 2)
num = num // 2
return string
def string_reverse(string_to_reverse):
return string_to_reverse[::-1]
if __name__ == '__main__':
# Type your code here.
# Your code must call int_to_reverse_binary() to get
# the binary string of an integer in a reverse order.
# Then call string_reverse() to reverse the string
# returned from int_to_reverse_binary().
num = int(input())
binary = int_to_reverse_binary(num)
print(string_reverse(binary))
Sheesh some of these examples are very complicated for a Python noob like me.
This is the way I did the lab(Please let me know what you think):
First, the way the lab wants to see it is in reverse(not correct binary but that's the way the lab wants to see it):
x = int(input())
bin_number = ''
while x > 0:
result = x % 2
bin_number = str(bin_number) + str(result)
x = x // 2
if x < 1:
break
continue
print(bin_number)
Second, prints the result in the correct order(but incorrect for the lab)
x = int(input())
bin_number = ''
while x > 0:
result = x % 2
bin_number = str(bin_number) + str(result)
rev_bin_number = bin_number[::-1]
x = x // 2
if x < 1:
break
continue
print(rev_bin_number)

Categories