How does python handle binary numbers?

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

asked Oct 6, 2009 at 3:37

3

You can convert between a string representation of the 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'

answered Oct 6, 2009 at 4:19

John La RooyJohn La Rooy

285k50 gold badges358 silver badges498 bronze badges

2

I think you're confused about what binary is. Binary and decimal are just different representations of a number - e.g. 101 base 2 and 5 base 10 are the same number. The operations add, subtract, and compare operate on numbers - 101 base 2 == 5 base 10 and addition is the same logical operation no matter what base you're working in. The fact that your python interpreter may store things as binary internally 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'll have to either write your own implementation or convert them using the int[binaryString, 2] function.

answered Oct 6, 2009 at 3:44

Steven SchlanskerSteven Schlansker

36.5k14 gold badges81 silver badges100 bronze badges

If you're talking about bitwise operators, then you're after:

~ Not
^ XOR
| Or
& And

Otherwise, binary numbers work exactly the same as decimal numbers, because numbers are numbers, no matter how you look at them. The only difference between decimal and binary is how we represent that data when we are looking at it.

answered Oct 6, 2009 at 3:54

SmasherySmashery

55.2k30 gold badges97 silver badges124 bronze badges

1

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

answered Oct 6, 2009 at 3:44

Pierre BourdonPierre Bourdon

10.1k4 gold badges32 silver badges27 bronze badges

Below is a re-write of a previously posted 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:]

Tom Aranda

5,67811 gold badges31 silver badges50 bronze badges

answered Dec 15, 2017 at 2:59

'''
I expect the intent behind this assignment was to work in binary string format.
This is absolutely doable.
'''

def compare[bin1, bin2]:
    return bin1.lstrip['0'] == bin2.lstrip['0']

def add[bin1, bin2]:
    result = ''
    blen = max[[len[bin1], len[bin2]]] + 1
    bin1, bin2 = bin1.zfill[blen], bin2.zfill[blen]
    carry_s = '0'
    for b1, b2 in list[zip[bin1, bin2]][::-1]:
        count = [carry_s, b1, b2].count['1']
        carry_s = '1' if count >= 2 else '0'
        result += '1' if count % 2 else '0'
    return result[::-1]

if __name__ == '__main__':
    print[add['101', '100']]

I leave the subtraction func as an exercise for the reader.

answered Feb 19, 2020 at 5:22

Gary02127Gary02127

4,7611 gold badge23 silver badges28 bronze badges

1

For example, 00000011 - 00000001 = 00000010

You can remove the zeroes and then add them again after you do your calculation! This works very easy.

If your binary is stored as a string then you can convert to int which will automatically strip the zeroes from the start. After you have your answer you can turn it back into a string and add the zeroes to the start.

Gino Mempin

20.7k24 gold badges84 silver badges111 bronze badges

answered Mar 4 at 2:28

Not sure if helpful, 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"]]

answered Jun 1, 2016 at 5:49

Mona JalalMona Jalal

31k61 gold badges210 silver badges374 bronze badges

x = x + 1 print[x] a = x + 5 print[a]

frhd

8,5785 gold badges23 silver badges40 bronze badges

answered Mar 14, 2018 at 13:19

0

I think you're confused about what binary is. Binary and decimal are just different representations of a number - e.g. 101 base 2 and 5 base 10 are the same number. The operations add, subtract, and compare operate on numbers - 101 base 2 == 5 base 10 and addition is the same logical operation no matter what base you're working in.

NathanOliver

164k27 gold badges270 silver badges376 bronze badges

answered Nov 12, 2015 at 13:19

1

How does Python deal with binary numbers?

Python | Binary numbers representation [assign, conversion, bitwise operations].
To assign binary values to the variable, we use prefix 0b or 0B with the binary value..
To convert a decimal value to the binary, we use bin[] Method, which is an inbuilt method in the Python..

How is binary represented in Python?

Binary uses bin[] and '0b'. Hexadecimal uses hex[] and '0x'. Octal uses oct[] and '0o'. The int[] function can be used to convert numbers into a base 10 integer from any base between 2 and 36 by changing the second parameter.

How does Python store data in binary file?

Write Bytes to File in Python Example 1: Open a file in binary write mode and then specify the contents to write in the form of bytes. Next, use the write function to write the byte contents to a binary file.

How does Python compare binary values?

Algorithm. Step 1 : Given two numbers. Step 2 : Convert both number into its binary using bin[] function and remove first two characters because of bin[]. Step 3 : Since binary representation of both numbers could differ in length so we will append zeroes in start of shorter string to make both string of equal length.

Chủ Đề