Binary numbers in Python

How can I add, subtract and compare binary numbers in Python without converting to decimal?

+46
python binary
Oct 06 '09 at 3:37
source share
7 answers

You can convert between the string representation of a binary using bin () and int ()

>>> bin(88) '0b1011000' >>> int('0b1011000', 2) 88 >>> >>> a=int('01100000', 2) >>> b=int('00100110', 2) >>> bin(a & b) '0b100000' >>> bin(a | b) '0b1100110' >>> bin(a ^ b) '0b1000110' 
+86
06 Oct '09 at 4:19
source share

I think you are confused about what a binary is. Binary and decimal numbers are just different representations of a number - for example. 101 base 2 and 5 base 10 are the same. The operations of adding, subtracting and comparing work with numbers - 101 base 2 == 5 base 10, and adding is the same logical operation, regardless of which base you work in. The fact that your python interpreter can store things as binary internal ones doesn't affect how you work with it - if you have an integer type, just use +, - etc.

If you have strings of binary digits, you will either have to write your own implementation or convert them using the int (binaryString, 2) function.

+9
Oct 06 '09 at 3:44
source share

If you are talking about bitwise operators, then you are after:

 ~ Not ^ XOR | Or & And 

Otherwise, binary numbers work exactly like decimal numbers, because numbers are numbers, no matter how you look at them. The only difference between decimal and binary is how we present this data when we look at it.

+7
Oct. 06 '09 at 3:54
source share

Binary, decimal, hexadecimal ... the base only matters when reading or printing numbers, adding binary numbers is the same as adding a decimal number: it's just a matter of presentation.

+3
Oct 06 '09 at 3:44
source share

The following is a rewrite of a previously published function:

 def addBinary(a, b): # Example: a = '11' + b =' 100' returns as '111'. for ch in a: assert ch in {'0','1'}, 'bad digit: ' + ch for ch in b: assert ch in {'0','1'}, 'bad digit: ' + ch sumx = int(a, 2) + int(b, 2) return bin(sumx)[2:] 
0
Dec 15 '17 at 2:59 on
source share

Not sure if useful, but I leave my solution here:

 class Solution: # @param A : string # @param B : string # @return a strings def addBinary(self, A, B): num1 = bin(int(A, 2)) num2 = bin(int(B, 2)) bin_str = bin(int(num1, 2)+int(num2, 2)) b_index = bin_str.index('b') return bin_str[b_index+1:] s = Solution() print(s.addBinary("11", "100")) 
-one
Jun 01 '16 at 5:49 on
source share

I think you are confused about what a binary is. Binary and decimal numbers are just different representations of a number - for example. 101 base 2 and 5 base 10 are the same. The add, subtract and compare operations work with numbers - 101 base 2 == 5 base 10, and adding is the same logical operation, regardless of which base you work in.

-four
Nov 12 '15 at
source share



All Articles