#include <stdio.h>
#include <stdint.h>
#define MODE_BITS_MASK 0b111
#define MODE_BITS_POS 0
#define SPEED_BITS_MASK 0b11111
#define SPEED_BITS_POS 3
#define RESERVED_BITS_MASK 0b11
#define RESERVED_BITS_POS 8
#define STATUS_BITS_MASK 0b111111
#define STATUS_BITS_POS 10
/*
* Function to pack mode, speed, and status into a 16-bit register.
* Reserved bits are set to 0.
*/
uint16_t pack_register(uint8_t mode, uint8_t speed, uint8_t status) {
return (uint16_t) (
((MODE_BITS_MASK & mode) << MODE_BITS_POS) | // Set Mode bits and shift to its position
((SPEED_BITS_MASK & speed) << SPEED_BITS_POS) | // Speed Mode bits and shift to its position
((RESERVED_BITS_MASK & 0) << RESERVED_BITS_POS) | // Reserved bits must be zero
((STATUS_BITS_MASK & status) << STATUS_BITS_POS) // Set Status bits and shift to its position
);
}
int main() {
uint8_t mode, speed, status;
scanf("%hhu %hhu %hhu", &mode, &speed, &status);
uint16_t reg = pack_register(mode, speed, status);
printf("%u", reg);
return 0;
}
This solution packs three fields—mode, speed, and status—into a 16-bit control register using bitwise operations. Each field is masked to its allowed bit width and shifted to its designated position within the register. Reserved bits are explicitly set to zero. The main function reads user input for each field, calls the packing function, and prints the resulting register value. This approach ensures efficient and clear encoding of multiple control parameters into a single register, suitable for hardware or protocol use.
Input
3 10 12
Expected Output
12371