0

Bad conversion binary integer number to string

I have tried parsing to char, binary and then to string, but it doesn't work in the proper way as I want to.

def xorGate(self):
    xorNumber= ''
    #receiving the 2 integers
    numBin1 = self.__sanearInput(self.inputParams[0])
    numBin2 = self.__sanearInput(self.inputParams[1])
    #act
    xorNumber=numBin1^numBin2
    #result
    xorNumber=str(xorNumber)
    self.outputParams.append(xorNumber)

I'm putting as a parameters "1000" & "1010". Finally, it parses the result to string getting "26" instead of "0010".

Marmeus
  • 3
  • 2
  • 2
    Your "binary" inputs are actually in decimal. `1000 ^ 1010` with base 10 is 26. – iz_ Jan 19 '19 at 22:36
  • To get actual binary values from those characters, use `'0b1000'` and `'0b1010'` or `int('1000', 2)` and `int('1010', 2)` or something like them. The best way depends on how you get those values into `inputParams`. – Rory Daulton Jan 19 '19 at 22:39

1 Answers1

0

Removing the class-method stuff that is irrelevant to the question, if I do this:

>>> numbin1 = 0b1000
>>> numbin2 = 0b1010
>>> xornumber = numbin1 ^ numbin2

I get

>>> xornumber
2
>>> bin(xornumber)
'0b10'

which is the right answer. What is happening is you are using the constants 1000 and 1010, which are decimal constants, and expecting Python to interpret them as binary just because you are using the ^ operator. Like this:

>>> bin(1000)
'0b1111101000'
>>> bin(1010)
'0b1111110010'
>>> bin(1000 ^ 1010)
'0b11010'

and 0b11010 is 26.

To interpret a user's input string of 1s and 0s as an integer represented in binary, consult this answer.

BoarGules
  • 16,440
  • 2
  • 27
  • 44