I wanted to create and analyze a 16-bit control word, this should be done in C code. Each bit should be evaluated, since each bit has a specific function. There can be an instruction that several bits should come and be analyzed at the same time. Does anyone have a solution for such a problem. So far I can check which bit is set, but I don't like the solution because I have 16 IF branches. Can this be simplified? Assuming the value 2049 comes, bit 0 and bit 11 are set. It would be good if there was a simple function for that. Each bit has a function whether HIGH or LOW.(at the end it should run on a microcontroller. I only used printf for testing)
Thank you for your help.
int main()
{
uint16_t NUM; //to store number
printf("Enter an 16 bits integer number: ");
scanf("%d",&NUM);
//checking bit status
if(NUM & (1<<0))
{
printf("Bit number %d is SET in number %d.\n",0,NUM);
}
if(NUM & (1<<1))
{
printf("Bit number %d is SET in number %d.\n",1,NUM);
}
if(NUM & (1<<2))
{
printf("Bit number %d is SET in number %d.\n",2,NUM);
}
if(NUM & (1<<3))
{
printf("Bit number %d is SET in number %d.\n",3,NUM);
}
if(NUM & (1<<4))
{
printf("Bit number %d is SET in number %d.\n",4,NUM);
}
if(NUM & (1<<5))
{
printf("Bit number %d is SET in number %d.\n",5,NUM);
}
if(NUM & (1<<6))
{
printf("Bit number %d is SET in number %d.\n",6,NUM);
}
if(NUM & (1<<7))
{
printf("Bit number %d is SET in number %d.\n",7,NUM);
}
if(NUM & (1<<8))
{
printf("Bit number %d is SET in number %d.\n",8,NUM);
}
if(NUM & (1<<9))
{
printf("Bit number %d is SET in number %d.\n",9,NUM);
}
if(NUM & (1<<10))
{
printf("Bit number %d is SET in number %d.\n",10,NUM);
}
if(NUM & (1<<11))
{
printf("Bit number %d is SET in number %d.\n",11,NUM);
}
if(NUM & (1<<12))
{
printf("Bit number %d is SET in number %d.\n",12,NUM);
}
if(NUM & (1<<13))
{
printf("Bit number %d is SET in number %d.\n",13,NUM);
}
if(NUM & (1<<14))
{
printf("Bit number %d is SET in number %d.\n",14,NUM);
}
if(NUM & (1<<15))
{
printf("Bit number %d is SET in number %d.\n",15,NUM);
}
if(NUM & (1<<16))
{
printf("Bit number %d is SET in number %d.\n",16,NUM);
}
return 0;
}
You are going to have to learn a lot about boolean operations if you want to move forward. There's lots of resources on the web.
The following may give you an idea of what you might need to think about. It is presented as-is.
Output: