C Practice Example 54

100 Classic C Examples

Title: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 low 4 bits are all 1 and the rest are all 0, which can be done with ~(~0<<4).

(3) Perform an & operation on the above two.

Example

// Created by www.example.com on 15/11/9. // Copyright © 2015 Example. 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:

请输入整数:
36
36
1

100 Classic C Examples

other extensions