How do you read binary numbers in python?

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 badges357 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.1k30 gold badges96 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,7511 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.6k24 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,5585 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 read binary data?

To open a file in binary format, add 'b' to the mode parameter. Hence the "rb" mode opens the file in binary format for reading, while the "wb" mode opens the file in binary format for writing. Unlike text files, binary files are not human-readable. When opened using any text editor, the data is unrecognizable.

How does Python handle binary numbers?

In Python, you can simply use the bin[] function to convert from a decimal value to its corresponding binary value. And similarly, the int[] function to convert a binary to its decimal value. The int[] function takes as second argument the base of the number to be converted, which is 2 in case of binary numbers.

How do you read a binary number?

The best way to read a binary number is to start with the right-most digit and work your way left. The power of that first location is zero, meaning the value for that digit, if it's not a zero, is two to the power of zero, or one. In this case, since the digit is a zero, the value for this place would be zero.

How do you decode a binary file in Python?

You can open the file using open[] method by passing b parameter to open it in binary mode and read the file bytes. open['filename', "rb"] opens the binary file in read mode.

Chủ Đề