Python Exercise Example 54
**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
(
'
%o
\t
%o
'
%
(
a
,
d
)
)
The output of the above example is:
input a number:
9
11 0
Python 100 Examples