In the MDR32(similar with STM32) microcontroller, there is a 16-bit STAT register that describes the ethernet status, the documentation says that 7..5 bits indicate the number of received packets, how can I get this value and save it in uint16_t
variable?
CodePudding user response:
Depending on how you read your notation, to get bits 5, 6 and 7 from an integer you can simply do:
auto ethStatus = (stat >> 5) & 7;
CodePudding user response:
If you shift the bits right 5 places then those 5..7 bits will be in positions 0..2. If you bitwise-and with value 0b0000000000000111U (bitmask), then all bits in positions 3..15 will be 0. This leaves you with the 3 bits that you wanted in the least significant positions:
unsigned ethernet_status = (STAT >> 5U) & 0b0000000000000111U;
You can generate the bitmask with N low bits by shifting 1 to left by N-1 and subtracting 1:
unsigned bit_first = 5;
unsigned bit_count = 3;
unsigned bit_mask = (1U << bit_count) - 1U;
unsigned ethernet_status = (STAT >> bit_first) & bit_mask;
You can store values in variables like this:
uint16_t variable = ethernet_status;