May the 4th be with you! It’s Jedi day, or Star Wars day, or whatever. Here’s a binary puzzle for you, one which demonstrates how the bitwise OR operator can be used to set bits in an integer value.
#include <stdio.h>
char *binbin(int n);
int main()
{
int input,result,bit,x;
bit = 1;
printf("Type a number between 0 and 255: ");
scanf("%d",&input);
printf("%s\n========\n",binbin(input));
for(x=0;x<8;x++)
{
result = bit | input;
printf("%s\n",binbin(result));
bit*=2;
}
return(0);
}
char *binbin(int n)
{
static char bin[9];
int x;
for(x=0;x<8;x++)
{
bin[x] = n & 0x80 ? '1' : '0';
n <<= 1;
}
bin[x] = '\0';
return(bin);
}
The code asks for input, a teensy int value (8 bits). That value is then manipulated using the logical OR for each bit position, 0 through 7.
Here's how the output looks when zero is input:
You can see the single bit cascading across each value. That bit is set sequentially no matter which value you input. The bit is always set by the bitwise |, which is why I call that operator the set-bit operator.