Home > Software engineering >  How to calculate 2 digits different number system than decimal [Python]
How to calculate 2 digits different number system than decimal [Python]

Time:11-28

I can't calculate 2 digits in different number system than decimal. Here's an example.

operation = "101   101"
result = eval(operation)
print(result)

and result is 202, but I would like to calculate it in binary where the result is 10 so whats the idea to do this. I know I can 0b before number but i can't do this in my situation. Is there like library or smth that do calculate it?

CodePudding user response:

if what you take as input is a string with some operation that you want to pass to eval, you can use a regular expression to append "0b" to the numbers and then pass that to eval

>>> import re
>>> operation = "101   101"
>>> re.sub("([01] )",r"0b\1",operation)
'0b101   0b101'
>>> eval('0b101   0b101')
10
>>> 

CodePudding user response:

You can tell int() function in which numerical base you want a string.

int('101', 2)   int('101', 2)
Out[2]: 10

CodePudding user response:

You can manually try adding the two numbers up using a 'for' cycle. You will be adding up every digit on their own. The way you can get each digit is by having that number which will give you the right digit of the number. There needs to be an 'if' statement in your cycle that checks whether when your adding up the two numbers their sum gets higher than the allowed value(which will be determined by the number system that you're using. in your case the sum of the two digits shouldn't be higher than 1). in the occasion that the sum does get higher you can handle that by saving it in another variable for the right time(which will be when your adding up the next digits in line) at the end you will need to have your number divided by 10 to go to the next digits.

  • Related