# Chapter 12: Operations on bits¶

### Program 12.1, Page number: 282¶

In [1]:
def main():

#Variable Declaration
word1=77
word2=150
word3=210

#Result
print(word1&word2)
print(word1&word1)
print(word1&word2&word3)
print(word1&1)

if __name__=='__main__':
main()

4
77
0
1


### Program 12.2, Page number: 286¶

In [2]:
def main():

#variable Declarations
w1=525
w2=707
w3=122

print("{0:5}  {1:5}  {2:5}".format(w1&w2,w1|w2,w1^w2))
print("{0:5}  {1:5}  {2:5}".format(~w1,~w2,~w3))
print("{0:5}  {1:5}  {2:5}".format(w1^w1,w1&~w2,w1|w2|w3))
print("{0:5}  {1:5}".format(w2&w3,w1|w2&~w3))
print("{0:5}  {1:5}".format(~(~w1&~w2),~(~w1|~w2)))

#Exchange variables
w1^=w2
w2^=w1
w1^=w2
print("w1={0:3}  w2={1:3}".format(w1,w2))

if __name__=='__main__':
main()

  513    719    206
-526   -708   -123
0     12    767
66    653
719    513
w1=707  w2=525


### Program 12.3, Page number: 288¶

In [3]:
def shift(value,n):
if(n>0):
value <<=n              #Left shift
else:
value >>=-n             #Right Shift

return value

def main():
#Variable Declaration
w1=177777
w2=444

#Result
print("{0:7}   {1:7}".format(shift(w1,5),w1<<5))
print("{0:7}   {1:7}".format(shift(w1,-6),w1>>6))
print("{0:7}   {1:7}".format(shift(w2,0),w2>>0))
print("{0:7} ".format(shift(shift(w1,-3),3)))

if __name__=='__main__':
main()

5688864   5688864
2777      2777
444       444
177776


### Program 12.4, Page number: 290¶

In [4]:
def rotate(value,n):

#Calculation
if(n>0):
n=n%32
else:
n=-(-n%32)

if(n==0):
result=value
elif(n>0):
bits=value>>(32-n)
result=value<<n|bits
else:
n=-n
bits=value<<(32-n)
result=value>>n|bits

return result

def main():
w1=0xabcdef00
w2=0xffff1122

print("%x"%rotate(w1,8))
print("%x"%rotate(w1,-16))
print("%x"%rotate(w2,4))
print("%x"%rotate(w2,-2))
print("%x"%rotate(w1,0))
print("%x"%rotate(w1,44))

if __name__=='__main__':
main()

abcdef00ab
abcdef00abcd
ffff1122f
3fffc448bfffc448
abcdef00
abcdef00abc