Checking bits

Hello,

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;
	
}
Last edited on
I don't understand why this compiles. main()'s signature should be either int main() or int main(int, char **).

Either way, bit n is the bit whose value in the binary expansion is 2^n, so the only bit in 4 that's 1 is bit 2, since 4 = 2^2.
Last edited on
It compiled through PowerShell when I passed in arguments along when executing the main.exe.

So when I perform, int temp = 1 << k, for example I want to get the 3rd bit to be 1 (0100), so k should be 2?

In programming it's often easier to start counting from zero.

1 << 0  ->  0001  first bit
1 << 1  ->  0010  second bit
1 << 2  ->  0100  third bit
1 << 3  ->  1000  fourth bit
Yes, you want k=1, so a function do do this is:
1
2
3
4
5
6
7
8
void checkBit(int value, int k) {
	int temp = 1 << (k-1);
	if(value & temp) {
		printf("true");
	} else {
		printf("false");
	}
}


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;
}

Topic archived. No new replies allowed.