07.07.2023 Views

Implementing-cryptography-using-python

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

52 Chapter 2 ■ Cryptographic Protocols and Perfect Secrecy

Table 2.2: Bitwise Operators

OPERATOR DESCRIPTION EXAMPLE

& (Binary AND)

Operator copies a bit to the result if it

exists in both operands.

| (Binary OR) Operator copies a bit if it exists in either

operand.

^ (Binary XOR)

~ (Binary Ones

Complement)

<< (Binary Left

Shift)

>> (Binary Right

Shift)

Operator copies the bit if it is set in one

operand but not both.

Operator is unary and has the effect of

“flipping” bits.

The left operand’s value is moved left

by the number of bits specified by the

right operand.

The left operand’s value is moved right

by the number of bits specified by the

right operand.

(a & b) (means 0000

1100)

(a | b) = 61 (means

0011 1101)

(a ^ b) = 49 (means

0011 0001)

(~a ) = -61 (means

1100 0011 in 2’s

complement form due to a

signed binary number)

a << 2 = 240 (means

1111 0000)

a >> 2 = 15 (means

0000 1111)

The bin() function in Python can be used to convert our integers 60 and 13

to their binary format. Type the following into the Python shell:

>>> a = 60

>>> b = 13

>>> print (bin(a))

0b111100

>>> print (bin(b))

0b1101

>>> print (bin(a &amp; b))

0b1100

>>> print (bin(a | b))

0b111101

>>> print (bin(a ^ b))

0b110001

>>> print (bin(~a))

-0b111101

>>> print (bin(a<<2))

0b11110000

>>> print (bin(a>>2))

0b1111

Each value maps as shown. Alphanumeric characters, such as A, B, C, can

also be converted to a binary format. The use of the ordinal function, ord(),

will give a numerical value to an ASCII letter. Examine the following example:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!