问题描述
我真的已经很努力在C int变量翻转位。我这样做,像这样:
I am trying REALLY hard to flip the bits in a C int variable. I am doing it like so:
input = 15;
input = ~input;
printf("%d", input);
但它总是显示为 -16
。它应该是 0
!如果 15
写成 1111
,为什么它返回 10000
?这是令人发狂!有人可以帮我!?
BUT IT ALWAYS SHOWS UP as -16
. It should be 0
! if 15
is written as 1111
, why is it returning 10000
?! This is maddening! Can somebody PLEASE help me!?
推荐答案
由于 INT
您的系统上是最有可能的一个32位的数字,所有位翻转,其中包括那名猥琐的人在零原来的号码:
Since int
on your system is most likely a 32-bit number, all bits are flipped, including the ones that were insignificant zeros in the original number:
00000000000000000000000000001111
变为
11111111111111111111111111110000
这是一个负数:最显著位 15
为零,因此它成为翻转时 1
This is a negative number: the most significant bit of 15
is zero, so it becomes 1
when flipped.
如果您想保留原来的号码只有位,你需要在号码的显著位置全部为掩盖,就像这样:
If you would like to keep only the bits of the original number, you need to mask with all ones in the significant positions of the number, like this:
printf("%d\n", input & 0xF);
和
ING与 0xF的
切断,除了过去四年所有位。
AND
ing with 0xF
"cuts off" all bits except the last four.
这篇关于ç位求反造成负面的输出:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!