什么是(x& 1)和(x> == 1)? [英] What is (x & 1) and (x >>= 1)?

查看:144
本文介绍了什么是(x& 1)和(x> == 1)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试进行赋值:在不使用sizeof()函数的情况下,找到无符号整数数据类型中的位数."

I am trying to do assignment: "Find the number of bits in an unsigned integer data type without using the sizeof() function."

我的设计是将整数转换为位数,然后对其进行计数.例如:10 is 10105 is 101

And my design is to convert the integer to bits and then to count them. For ex: 10 is 1010 and 5 is 101

将整数转换为位表示会显示以下内容:

Converting integer to a bit representation shows something like this:

do
{ 
    Vec.push_back( x & 1 ) 
} 
while ( x >>= 1 );

我不想只复制粘贴内容.当我使用F-10时,我看到(x & 1)在做什么,但是我不知道它是名字还是它的工作方式(比较一下?).我也知道>=哪个大于或等于",但是x >>= 1是什么?

I don't want to just copy paste stuff. When I use F-10 I see what (x & 1) is doing but I don't know it is name or how it does its job(compare something?). Also I know >= which "greater than or equal" but what is x >>= 1?

注意:标记的重复项是JavaScript而不是C ++

Note: The marked duplicate is a JavaScript and not C++

推荐答案

这些是按位运算符( x & 1产生的值是10,具体取决于x的最低有效位:如果最后一位是1,则x & 1的结果是1 ;否则为0.这是按位与运算.

x & 1 produces a value that is either 1 or 0, depending on the least significant bit of x: if the last bit is 1, the result of x & 1 is 1; otherwise, it is 0. This is a bitwise AND operation.

x >>= 1的意思是将x设置为自身向右移动一位".移位后,该表达式的值将为新的x值.

x >>= 1 means "set x to itself shifted by one bit to the right". The expression evaluates to the new value of x after the shift.

注意:对于无符号类型的值,移位后的最高有效位的值为零.对于有符号类型的值,最高有效位是从移位之前的值的符号位复制而来的,这是 sign扩展的一部分,因此,如果x是有符号类型,则循环将永远不会结束,并且初始值为负.

Note: The value of the most significant bit after the shift is zero for values of unsigned type. For values of signed type the most significant bit is copied from the sign bit of the value prior to shifting as part of sign extension, so the loop will never finish if x is a signed type, and the initial value is negative.

这篇关于什么是(x& 1)和(x> == 1)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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