位运算

来源:互联网 发布:出售淘宝花呗店铺 编辑:程序博客网 时间:2024/06/08 03:09

题目:
Write C expressions that evaluate to 1 when the following conditions are true, and
to 0 when they are false. Assume x is of type int.
A. Any bit of x equals 1.
B. Any bit of x equals 0.
C. Any bit in the least significant byte of x equals 1.
D. Any bit in the most significant byte of x equals 0.

代码:

#include <stdio.h>#include <stdlib.h>#include <string.h>/* 如果 x 所有位都为 1 ,返回 1 ,否则,返回 0 */bool x_equals_1(int x) {     return !(~x);}/* 如果 x 所有位都为 0 ,返回 1 ,否则,返回 0 */bool x_equals_0(int x) {    return !x;}/* 如果 x 的最低有效位都为 1 ,返回 1,否则,返回 0 */bool x_lsb_equals_1(int x) {    return x_equals_1(x | 0xFFFFFF00);}/* 如果 x 的最高有效位都为 0 ,返回 1 ,否则,返回 0 */bool x_msb_equals_0(int x) {    return x_equals_1((x | 0x00FFFFFF) ^ 0xFF000000);}int main() {    int x = 0x000000FF;    printf("x=%x\n", x);    printf("x_equals_1          %d\n", x_equals_1(x));    printf("x_equals_0          %d\n", x_equals_0(x));    printf("x_lsb_equals_1      %d\n", x_lsb_equals_1(x));    printf("x_msb_equals_0      %d\n", x_msb_equals_0(x));    return 0;}

注意:
运算符!是逻辑取反,比如:如果 x! = 0 ,则 !x = 0 ,如果 x = 0,则!x = 1
运算符~是按位取反,比如:如果二进制数 x = 0000 0000,则~x = 1111 1111,如果x = 1100 1101,则~x = 0011 0010

0 0