Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Exercise Example 54

Python Exercise Example 54

Python 100 Examples Python 100 Examples

**Problem:** Extract bits 4 to 7 of an integer a, starting from the right.

**Program Analysis:** This can be considered as follows:
(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 an & operation on the two above.

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 of the above example is:


input a number:
9
11    0

Python 100 Examples Python 100 Examples