This is C and I cannot use any libraries or use C++.
I'm writing simple code to check if a bit, k, in an integer is 1. I looked at some code online and it appears to be the same as mine. However, I do not understand why my code is not returning my desired results.
For example, if I pass 4 as an integer and 3 as the bit to be checked then it is supposed to print out true. However it prints out false.
Can anyone assist me in understanding why this piece of code is not returning the correct results or this code in general?
1 2 3 4 5 6 7 8 9 10 11 12
int main(int value, int k) {
int temp = 1 << k;
if(value & temp) {
printf("true");
} else {
printf("false");
}
return 0;
}
As for your main() program, you're probably getting garbage in k because you've declared it wrong. As an experiment, try printing value and k at the top of main. What you really want is:
1 2 3 4 5 6 7 8 9 10 11 12
int main(int argc, char **argv)
{
int k, value;
if (argc <3) {
printf("usage: %s value k\n", argv[0]); // argv[0] is the program name
return 1;
}
value = atoi(argv[1]);
k = atoi(argv[2]);
checkBit(value, k);
return 0;
}