简体   繁体   English

按位运算符

[英]bitwise operators

I'm beginner with C and I am learning on my own. 我是C的初学者,我自己学习。 I am trying to convert an int to binary for bitwise operations, and I am not really sure how to do it? 我正在尝试将int转换为二进制以进行按位运算,但我不确定该怎么做? I have tried to use mod and other mathematics to do it, but I have been unsuccessful. 我尝试使用mod和其他数学方法来执行此操作,但未成功。 I have searched around and have not found a clear way of this. 我到处搜寻,但没有找到明确的方法。 Please assist. 请协助。

You don't need to do any conversion of an int to use bitwise operators on it. 您无需对int进行任何转换即可在其上使用按位运算符。 They automatically work on the bits that compose the int . 它们自动处理组成int

If you want to view the binary representation of a number, you can use (assuming the 8 least significant bits)... 如果要查看数字的二进制表示形式,可以使用(假设8个最低有效位)...

int num = 4;

int i;

for (i = 7; i >= 0; i--) {
    printf("%d", (num >> i) & 1);
}

CodePad . 键盘

This uses bitwise operators >> (right shift) and & (and). 这使用按位运算符>> (右移)和& (与)。

It's already represented in the computer as binary! 它已经在计算机中表示为二进制! (Unless you have one of those ternary computers.) So go ahead and use bitwise operators on your int s. (除非您拥有这些三元计算机之一。)因此,继续在int上使用按位运算符。 (Works even if you do have one of those ternary computers.) (即使您确实拥有这些三元计算机之一, 可以使用。)

See? 看到? It works! 有用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM