C Exercise 54
100 Classic C Language Examples
**Problem:** Extract bits 4 to 7 of an integer a, starting from the right end.
**Program Analysis:** This can be considered as follows:
(1) First shift a right by 4 bits.
(2) Set a number whose low 4 bits are all 1 and the rest all 0, which can be done with ~(~0<<4)
(3) Perform an & operation on the two above.
Example
// Created by www.runoob.com on 15/11/9.
// Copyright (c) 2015 Runoob Tutorial. All rights reserved.
//
#include
<
stdio.h
int
main
(
)
{
unsigned
a
,
b
,
c
,
d;
printf
(
"
Please enter an integer:
\
n
"
)
;
scanf
(
"
%o
"
,&
a
)
;
b
=
a
4
;
c
=~
(
~
0
<<
4
)
;
d
=
b
&
c
;
printf
(
"
%o
\
n%o
\
n
"
,
a
,
d
)
;
return
0
;
}
The output of the above example is:
Please enter an integer:
36
36
1