[英]How to ignore specific bits in a 32-bit integer
I am polling a 32-bit register in a motor driver for a value.我正在轮询电机驱动器中的 32 位寄存器以获取值。
Only bits 0-9 are required, the rest need to be ignored.只需要 0-9 位,rest 需要忽略。
How do I ignore bits 10-31?如何忽略 10-31 位?
In order to poll the motor driver for a value, I send the location of the register, which sends back the entire 32-bit number.为了轮询电机驱动器的值,我发送了寄存器的位置,它发回了整个 32 位数字。 But I only need bits 0-9 to display.但我只需要显示 0-9 位。
Serial.println(sendData(0x35, 0))
If you want to extract such bits then you must mask the whole integer with a value that keeps just the bits you are interested in.如果要提取此类位,则必须使用仅保留您感兴趣的位的值屏蔽整个 integer。
This can be done with bitwise AND ( &
) operator, eg:这可以使用按位 AND ( &
) 运算符来完成,例如:
uint32_t value = reg & 0x3ff;
uint32_t value = reg & 0b1111111111; // if you have C++11
You do a bitwise and
with a number with the last 10 bits set to 1. This will set all the other bits to 0. For example:您按and
执行一个数字,最后 10 位设置为 1。这会将所有其他位设置为 0。例如:
value = value & ((1<<10) - 1);
Or或者
value = value & 0x3FF;
Rather than Serial.println()
I'd go with Serial.print()
.而不是Serial.println()
我会 go 与Serial.print()
。 You can then just print out the specific bits that you're interested in with a for loop.然后,您可以使用 for 循环打印出您感兴趣的特定位。
auto data = sendData(0x35, 0);
for (int i=0; i<=9; ++i)
Serial.print(data && (1<<i));
Any other method will result in extra bits being printed since there's no data structure that holds 10 bits.任何其他方法都会导致打印额外的位,因为没有包含 10 位的数据结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.