0

I'm a little bit confused about the behavior of the bitwise xor operator. Why, if xor is possible only with binary data, am I able to use xor with decimal numbers?

For example:

fs='a'
sn='k'    
ord(fs) ^ ord(sn)

ord(fs) gives me an ASCII code that is not binary.

1
  • 1
    Why do you think a ascii code isn't binary? Commented Feb 17, 2018 at 17:33

2 Answers 2

1

According to the Python 3 documentation for built-in functions, ord() returns an integer:

Given a string representing one Unicode character, return an integer representing the Unicode code point of that character. For example, ord('a') returns the integer 97 [...]

This integer is represented by a sequence of bits, and so it is a valid operand to the bitwise XOR operator.

Edit

Python interprets the value 97 as an integer. And, internally, the integer numeric type is represented as a sequence of bits. The integer type is described in Numeric Types. Another section of that same documentation explains Bitwise Operations on Integer Types, and it states that

Bitwise operations only make sense for integers.

That is, bitwise operations on any other type, including a string, are invalid in Python.

So ord() returns an integer. Which is represented internally as a sequence of bits. Although its type is not explicitly "binary," Python still defines the bitwise XOR operator for integers.

To be clear, all values are represented internally as a sequence of bits. It's just that Python only defines the bitwise XOR operator for integers.

Sign up to request clarification or add additional context in comments.

1 Comment

Still a little confused, string is a sequence of bit, but in python if I type 97 is integer not bit right?
0

It works exactly as designed, just that you need to assign it to a variable, and print them.

You can convert them (=integers) back to a binary strings like this '{0:b}'.format(some_integer). The .zfill(8) in the below example is to "zero fill left to 8 chars" to align them up neatly.

Example:

fs='a' 
sn='k'

#assign result to variable
r = ord(fs) ^ ord(sn)

print('fs=', str(ord(fs)).rjust(3), '{0:b}'.format(ord(fs)).zfill(8))
print('sn=', str(ord(sn)).rjust(3), '{0:b}'.format(ord(sn)).zfill(8))
print('r =', str(r).rjust(3), '{0:b}'.format(r).zfill(8))

output:

fs=  97 01100001
sn= 107 01101011
r =  10 00001010

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.