〜运算符用C [英] ~ operator in C
本文介绍了〜运算符用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
该程序的输出为-13。我从来没有完全理解〜运营商C.为什么它给-13作为输出?如何限制〜多项操作者只需4位?
#包括LT&;&stdio.h中GT;
#包括LT&;&CONIO.H GT;
诠释的main()
{
int类型的= 12;
A =〜一;
的printf(%d个,一);
残培();
返回;
}
解决方案
要限制效果位指定数目的,只要使用按位掩码,例如:
的#include<&stdio.h中GT;诠释主要(无效){
int类型的= 16; / * 10000 *二进制/
INT B =〜A; / *威尔间preT b以-17的补* /
INT C =(A和〜0xF的)| (〜A和0xF的); / *将限制运营商最右边的4位,
所以00000 01111变得和c将成为
11111,不是11 ... 101111,所以C将是31 * / 的printf(一个是%D,B的%D,C为%d \\ n,A,B,C);
返回0;
}
输出:
保罗@地方:〜/ src目录/ C /划伤$ ./comp
一个是16,b为-17,c为31
保罗@地方:〜/ src目录/ C / $从零开始
The output of this program is -13. I have never fully understood ~ operator in C. Why does it give -13 as output? How to limit ~ operator to just 4 bits of a number?
#include<stdio.h>
#include<conio.h>
int main()
{
int a = 12;
a = ~a;
printf("%d",a);
getch();
return;
}
解决方案
To limit the effect to a specified number of bits, just use bitwise masks, e.g.:
#include <stdio.h>
int main(void) {
int a = 16; /* 10000 in binary */
int b = ~a; /* Will interpret b as -17 in two's complement */
int c = (a & ~0xF) | (~a & 0xF); /* Will limit operator to rightmost 4 bits,
so 00000 becomes 01111, and c will become
11111, not 11...101111, so c will be 31 */
printf("a is %d, b is %d, c is %d\n", a, b, c);
return 0;
}
Outputs:
paul@local:~/src/c/scratch$ ./comp
a is 16, b is -17, c is 31
paul@local:~/src/c/scratch$
这篇关于〜运算符用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文