按位NOT运算符是否返回意外和负值? [英] Bitwise NOT operator returning unexpected and negative value?

查看:62
本文介绍了按位NOT运算符是否返回意外和负值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Bitwise NOT来获取整数值,但是我没有得到我期望的结果.

I'm trying to get the value of an integer using Bitwise NOT, but i'm not getting what i expected.

#include <stdio.h>

int main(){
    int i = 16;
    int j = ~i;
    printf("%d", j);
    return 0;
}

不是16应该是:

00000000000000000000000000010000

因此〜16应该是:

11111111111111111111111111101111

为什么我没有得到我期望的结果,为什么结果是负数?

Why i'm not getting what i expected and why the result is negative?

这就是我想要做的:

我有一个数字27,例如:

I have a number for exemple 27 which is:

00000000000000000000000000011011

并希望检查每一位是1还是0.

And want to check every bit if it's 1 or 0.

所以我需要举例说明这个值

So i need to get for exemple this value

11111111111111111111111111110111

使用第二个来检查第一个的第3位是否设置为1.

The use second one to check if the 3rd bit of the first is set to 1.

推荐答案

并希望检查每一位是1还是0.

And want to check every bit if it's 1 or 0.

要检查单个位,您不需要输入数字,而要使用适当的位掩码对其进行相加:

To check an individual bit, you don't NOT the number, you AND it with an appropriate bit mask:

if ((x & 1) != 0) ... // bit 0 is 1
if ((x & 2) != 0) ... // bit 1 is 1
if ((x & 4) != 0) ... // bit 2 is 1
if ((x & 8) != 0) ... // bit 3 is 1
...
if ((x & (1 << n)) != 0) ... // bit n is 1
...
if ((x & 0x80000000) != 0) ... // bit 31 is 1

这篇关于按位NOT运算符是否返回意外和负值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆