Converting a calculated decimal number into 8 bit binary - python

I am currently making a python program that is byte adder related, it will prompt the user to enter 2 integers, add them together and if it's within the range of the actual size of a byte (0 to 255) display that number and also give the corresponding value in its 8 bit binary form, for example, the calculation is equal to 1, show the binary number which python declares as the correct one.
This is the task that I am doing ~
"The program must check the input data for the data type permitted and the data value limitations (the value of the integer must not exceed the actual size of byte-coded integers, i.e. min 00000000 and max 11111111 in Base 2 or min 0 and max 255 in Base 10 for positive integers" Input in both binary and decimal format with conversion to binary
def add():
Num1 = int(input("Input the first number between 0 and 255, the calculated answer must not be above 255: "))
Num2 = int(input("Input the second number between 0 and 255, the calculated answer must not be above 255: "))
calculatedanswer = Num1+Num2
if calculatedanswer >= 0 and calculatedanswer <=255:
print("The answer in decimal is" ,calculatedanswer,)
**bin(calculatedanswer)**
elif calculatedanswer < 0 and calculatedanswer >255:
print("Please ensure the added numbers are above 0 and below 255")
add()
This is my code so far, I have no trouble getting it to display the standard decimal number, but I really can't get the bin(calculatedanswer) to show the binary equivalent of it. I tried using this method that I found on YouTube.
I think my main problem here is my lack of understanding of how "bin" works on python as this is really the first time I am using it.
I have put asterisks around the line that I am having trouble with.

You do have to print the value:
>>> print(bin(160)) # This version gives the 0b prefix for binary numbers.
0b10100000
>>> print(format(160,'08b')) # This specifies leading 0, 8 digits, binary.
10100000
>>> print('{:08b}'.format(160)) # Another way to format.
10100000
>>> print(f'{160:08b}') # Python 3.6+ new f-string format.
10100000

One option for printing it would be to slice off the 0b portion of the result, which I assume is what you mean when you say you are having problems with the bin function.
Try this:
print(bin(calculatedanswer)[2:]))

Related

How to keep leading zero when returning value from modulo Python

I want to build a program which allows the user to input a number then make that number exponent of 2. Also user inputs how many last digits of final number wants to see. This is my code:
exponent = eval(input('Type in exponent '))
lastDigits = eval(input('Type in how many digits you want to see'))
number = 2**exponent
print(number /int(('1'+('0'*lastDigits))))
The output for example is:
Type in exponent = 10
Type in how many digits you want to see = 3
Here comes the problem.
If my exponent is 10 that means 2**10 = 1024
I want to see 3 last digits so that is 024 but Python doesn't keep this leading zero so I just get 24. How can I fix this?
I would use string operations instead of integer operations:
exponent = int(input('Type in exponent '))
lastDigits = int(input('Type how many digits you want to see '))
number = 2 ** exponent
cropped = str(number)[-lastDigits:]
print(cropped) # Result: "024"
I'm essentially just slicing off all but the last lastDigits characters in the string representation of number, that way we include any leading zeroes.
I also switched to using int casting instead of the eval function, because the eval function could be potentially dangerous if anyone decides to put something destructive into the input.

int(str) of a huge number

if i have a number that is too big to be represented with 64 bits so i receive a string that contains it.
what happens if i use:
num = int(num_str)
i am asking because it looks like it works accurately and i dont understand how, does is allocate more memory for that?
i was required to check if a huge number is a power of 2. someone suggested:
def power(self, A):
A = int(A)
if A == 1:
return 0
x =bin(A)
if x.count('1')>1:
return 0
else:
return 1
while i understand why under regular circumstances it would work, the fact that the numbers are much larger than 2^64 and it still works baffles me.
According to the Python manual's description on the representation of integers:
These represent numbers in an unlimited range, subject to available (virtual) memory only. For the purpose of shift and mask operations, a binary representation is assumed, and negative numbers are represented in a variant of 2’s complement which gives the illusion of an infinite string of sign bits extending to the left.

Converting Binary to Decimal in python (without built in binary function)

Alrighty, first post here, so please forgive and ignore if the question is not workable;
Background:
I'm in computer science 160. I haven't taken any computer related classes since high school, so joining this class was a big shift for me. It all seemed very advanced. We have been working in Python and each week we are prompted to write a program.
I have been working with this problem for over a week and am having a hard time even starting.
The prompt is to read an integer containing only 1's and 0's,
process the binary number digit by digit and report the decimal equivalent. Now, I have gotten some tips from a classmate and it sent me at least in a direction.
Set up a couple of counters;
using the % operator to check the remainder of the number divided by 2, and slicing off the last number (to the right) to move on to and process the next digit.
I am having an incredibly hard time wrapping my head around what formula to use on the binary digits themselves which will convert the number to decimal.
setbitval = 0
counter = 0
user = int(input("enter a binary value. "))
if user % 2 == 1:
user = (user/10) - .1
setbitval += 1
This is all I've got so far.. My thinking is getting in the way. I've searched and searched, even through these forums.
Any information or thoughts are extremely appreciated,
T
Edit: okay guys, everyone's help has been extremely useful but I'm having a problem checking if the user input is not a binary number.
for i in reversed(bits):
decimal += 2**counter * int(i)
counter += 1
This is the formula someone here gave me and I've been trying different iterations of "for i in bits: if i in bits: != 0 or 1" and also "if i in bits: >= 1 or <=0".
Any thoughts?
you can use this code:
binary= raw_input("Binary: ")
d= int(binary, 2)
print d
To convert binary value to decimal you need to do the following:
Take the least significant bit and multiply it by 2^0, then take the next least significant beat and multiply it by 2^1, next one by 2^2 and so on...
Let's say, for example you need to convert a number 1010 to decimal:
You would have 0*2^0 + 1*2^1 + 0*2^2 + 1*2^3 = 0 + 2 + 0 + 8 = 10
So in your python code, you need to:
read the int that the user inputted (representing the binary value).
convert that int and convert it to string, so you can break it into list of digits
make a list of digits from the string you created (a list int python can be created from a string not an int, that's why you need the conversion to string first)
go trough that list of bits in reverse and multiply every bit by 2^k, k being the counter starting from 0
Here's the code that demonstrates what I just tried to explain:
user_input = int(input("enter a binary value"))
bits = list(str(user_input))
decimal = 0
counter = 0
for i in reversed(bits):
decimal += 2**counter * int(i)
counter+=1
print 'The decimal value is: ', decimal
I'll agree this is close to the "code this for me" territory, but I'll try to answer in a way that gets you on the right track, instead of just posting a working code snippet.
A simple way of doing this is just to use int()'s base argument, but I'm guessing that is disallowed.
You already have a way of testing the current bit in your question, namely checking whether n % 2 == 1. If this is the case, we need to add a power of two.
Then, we need some way of going to the next bit. In binary, we would use bit shifts, but sadly, we don't have those. a >> b is equivalent to a // (2**b) - can you write a decimal equivalent to that?
You also need to keep a counter of which power of two the current bit represents, a loop, and some way of detecting an end condition. Those are left as exercises to the reader.
I’d recommend reading the following articles on Wikipedia:
https://en.wikipedia.org/wiki/Radix
https://en.wikipedia.org/wiki/Binary_number
The first one gives you an idea how the numeral systems work in general and the second one explains and shows the formula to convert between binary and decimal systems.
Try to implement the solution after reading this. That’s what I did when I dealt with this problem. If that doesn’t help, let me know and I’ll post the code.
Hopefully, this code clarifies things a bit.
x = input("Enter binary number: ").strip()
decimal = 0
for i in range(len(x)):
decimal += int(x[i]) * 2**abs((i - (len(x) - 1)))
print(decimal)
This code takes in a binary number as a string, converts it to a decimal number and outputs it as an integer. The procedure is the following:
1st element of binary number * 2^(length of binary number - 1)
2nd element of binary number * 2^(length of binary number - 2)
and so on till we get to the last element and ...2^0
If we take number 10011, the conversion using this formula will look like this:
1*2^4 + 0*2^3 + 0*2^2 + 1*2^1 + 1*2^0, which equals to 19.
This code, however, assumes that the binary number is valid. Let me know if it helps.
Another implementation using while loop might look like this. Maybe it'll be easier to understand than the code with the for loop.
x = input("Enter binary number: ").strip()
decimal = 0
index = 0
exp = len(x) - 1
while index != len(x):
decimal += int(x[index]) * 2**exp
index += 1
exp -= 1
print(decimal)
In this one we start from the beginning of the number with the highest power, which is length of binary number minus one, we loop through the number, lowering the power and changing index.
Regarding checking if number is binary.
Try using helper function to determine if number is binary and then insert this function inside your main function. For example:
def is_binary(x):
""" Returns True if number x is binary and False otherwise.
input: x as a string
"""
for i in list(x):
if i not in ["1", "0"]:
return False
return True
def binary_decimal(x):
""" Converts binary to decimal.
input: binary number x as a string
output: decimal number as int
"""
if not is_binary(x):
return "Number is invalid"
decimal = 0
for i in range(len(x)):
decimal += int(x[i]) * 2**abs((i - (len(x) - 1)))
return decimal
The first function checks if number consists only of ones and zeros and the second function actually converts your number only if it's binary according to the first function.
You can also try using assert statement or try / except if you'd better raise an error if number is not binary instead of simply printing the message.
Of course, you can implement this solution without any functions.

Converting bitstring to 32-bit signed integer yields wrong result

I am trying to solve a challenge on this site. I have everything correct except I can't properly convert a bitstring to its 32-bit signed integer representation.
For example I have this bitstring:
block = '10101010001000101110101000101110'
My own way of converting this bitstring to 32-bit signed integer: I partially remember from school that first bit is the sign bit. If it is 1 we have negative number and vice versa.
when I do this, it gives me the number in base 10. It just converts it to base 10:
int(block, 2) #yields 2854414894
I have tried excluding the first bit and convert remaining 31 length bitstring, after that checked the first bit to decide whether this is negative number or not:
int(block[1:32], 2) #yields 706931246
But the correct answer is -1440552402. What operation should I do to this bitstring to get this integer? Is it relevant if the byte order of the system is little endian or big endian? My system is little endian.
In python there's no size for integers, so you'll never get a negative value with a high order 1 bit.
To "emulate" 32-bit behaviour just do this, since your 2854414894 value is > 2**31-1 aka 0x7FFFFFFF:
print(int(block[1:32], 2)-2**31)
you'll get
-1440552402
You're right that the upper bit determines sign, but it's not a simple flag. Instead, the whole character of negative numbers is inverted. This is a positive number 1 (in 8 bits):
00000001
This is a negative 1:
11111111
The upshot is that addition and subtraction "wrap around". So 4 - 1 would be:
0100 - 0001 = 0011
And so 0 - 1 is the same as 1_0000_0000 - 1. The "borrow" just goes off the top of the integer.
The general way to "negate" a number is "invert the bits, add 1". This works both ways, so you can go from positive to negative and back.
In your case, use the leading '1' to detect whether negation is needed, then convert to int, then maybe perform the negation steps. Note, however, that because python's int is not a fixed-width value, there's a separate internal flag (a Python int is not a "32-bit" number, it's an arbitrary-precision integer, with a dynamically allocated representation stored in some fashion other than simple 2's complement).
block = '10101010001000101110101000101110'
asnum = int(block, 2)
if block[0] == '1':
asnum ^= 0xFFFFFFFF
asnum += 1
asnum = -asnum
print(asnum)
You should check for when the input value is out of the positive range for 32 bit signed integers:
res = int(block, 2)
if res >= 2**31:
res -= 2**32
So first you interpret the number as an unsigned number, but when you notice the sign bit was set ( >= 2^31 ), you subtract 2^32 so to get the negative number.

How to describe the maths behind this function

This is a Decimal to Binary converter. I need help explaining the math behind is as I don't have a clue how to explain all the Shifts etc.
number = int(raw_input("Enter the Number:"))
binary = ''
while number > 0:
binary = str(number % 2) + binary
number >>=1
print(binary)
The loop builds up a string which represents a binary value.
str(number % 2) finds the lowest bit of the number (either 0 or 1).
binary = str(number % 2) + binary adds the bit to the left end of string binary
number >>=1 removes the low bit now that we're done with it
while number > 0 continues until the number is 0
Suppose you are converting 56 to binary.
When right shift by 1 bit, 56 (111000) becomes 28(011100)
Note: The right shift operator causes the bit pattern in the first operand to be shifted right the number of bits specified by the second operand. Bits vacated by the shift operation are zero-filled for unsigned quantities
Like this, the variable, number is right shifted by 1 till it is greater than 1 and every time, the remainder of number divided by 2 (this will be 0 or 1 always) is appended to the result variable, binary
Finally, the variable binary will have the binary equvalent

Categories

Resources