Python Practice Example 54

Python 100例Python 100 Examples

Problem:Take the 4th to 7th bits from the right end of an integer a.

Program analysis:You can consider it this way:
(1) First shift a right by 4 bits.
(2) Set a number whose lower 4 bits are all 1 and the rest are all 0. You can use ~(~0<<4)
(3) Perform the & operation on the above two.

Example

#!/usr/bin/python # -*- coding: UTF-8 -*- if __name__ == '__main__': a = int(input('input a number:\n')) b = a >> 4 c = ~(~0 << 4) d = b & c print ('%o\t%o' %(a,d))

The output result of the above example is:

input a number:
9
11    0

Python 100例Python 100 Examples

Other extensions