简体   繁体   中英

How to ignore specific bits in a 32-bit integer

I am polling a 32-bit register in a motor driver for a value.

Only bits 0-9 are required, the rest need to be ignored.

How do I ignore bits 10-31?

Image of register bits

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. But I only need bits 0-9 to display.

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.

This can be done with bitwise AND ( & ) operator, eg:

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:

value = value & ((1<<10) - 1);

Or

value = value & 0x3FF;

Rather than Serial.println() I'd go with Serial.print() . You can then just print out the specific bits that you're interested in with a for loop.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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