Add two binary numbers

i need to add two binary number.

in the first place how i display a binary number in julia ? i try a lot things but doesn’t work
like , parse(Int,"111",2) or Int(0b110111)
in python the code is like that

    def addBinary(self, a, b) -> str:

        x,y = int(a,2),int(b,2) # **how i can do that in julia ??**
        if a=='0' : return b
        if b=='0' : return a
        while y:
            #x, y = x ^ y, (x & y) << 1
            result = x^y #XOR  =(1+0)=1 , 1+1=0
            carry = (x&y) << 1 # just in 1+1 = 1 ,all zero # **in julia they have a and ?** 
            print(result , carry)
            x , y = result , carry
        return bin(x)[2:]

How is it represented? If you are using 0b11 etc to construct it, that will just use the applicable <:Unsigned type, which of course has + defined in Base, so there is no need to do anything special.


1 Like

parse and Int have nothing to do with displaying. Every number is a binary number, the syntax 0b110111 (base 2) make easy you pass the number 55 (base 10) to the program while looking at its binary representation, but it is a number like any other and it is represented in binary inside the computer.

Are you talking about strings representing binary numbers with characters '0' and '1'? To make them an Int you can use parse(Int, "01011", base = 2). I do not know, however, if there is a standard library function in Julia that does transform the number in a String of '0' and '1' (base 2). The Prinf.@sprintf does not accept any format identifier that prints the number base 2.


In Julia the code is like this:

julia> 0b1 + 0b11

In case you want to see it in the true binary representation, use bitstring(n):

julia> bitstring(0b1 + 0b11)