位运算

题目:
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值