# Thread: C Read an integer and count 1s only at positions 2, 4, 6 , 8 of the binary

1. OK I solved it. As I said I had to solve that only with ONE variable, and count only the bits at positions 2,4,6,8 of a binary code, not ALL THE BITS IN A BINARY CODE. So I CANNOT use a function, or for loops or while loops, because I would need to use more variables. Here is my code:

Code:
```#include <stdio.h>
int main()
{
int x ;

printf("Enter number: ");
scanf("%d",&x);

printf("%d\n", x & 1);  //pos 1
printf("%d\n", (x >> 1) & 1); //pos 2
printf("%d\n", (x >> 2) & 1); //pos 3
printf("%d\n", (x >> 3) & 1); //pos 4
printf("%d\n", (x >> 4) & 1); //pos 5
printf("%d\n", (x >> 5) & 1); //pos 6
printf("%d\n", (x >> 6) & 1); //pos 7
printf("%d\n", (x >> 7) & 1); //pos 8

printf("\n\nTotal: %d\n", ((x >> 1) & 1)+((x >> 3) & 1)+((x >> 5) & 1)+((x >> 7) & 1));

return 0;
}```

THANK YOU ALL FOR TRYING TO HELP ME ! Code:
```/** tallybit.c read in a integer value, as a 4-Byte(32Bit) integer
* and counts the digits where are set and not set.
* If you read in a negativ integer it shows how does it looks
* in binary(Two's complement)
* https://en.wikipedia.org/wiki/Signed_number_representations
*
* written by Josef Franz Wismeth, in upper palatinate, bavaria
*
* last changes at 2018 December, 26th */

#include <stdio.h>
#include <stdlib.h>

/** counts the number of bits of argument 1, argument_2 = number of bits are set, argument_2 number of bits are not set*/
void tallybin(int intnumber, unsigned int (*bits_set), unsigned int (*bits_not_set))
{
unsigned int i, grot = 0, result, bits_are_on = 0, bits_are_off = 0, bitsize = 0;

bitsize = ((sizeof(int)) * 8);

grot = 1 << (bitsize - 1);

/// can set the line to a comment
printf("size of argument 1 in bit: %d\n", bitsize);

for (i = 0; i <= (bitsize - 1); i++)
{
result = (unsigned int)intnumber & grot;

/// shows the bits, can set this two lines to a comment
if (result) printf("1");
else printf("0");

grot >>= 1;
if (result) bits_are_on++;
else bits_are_off++;
}

(*bits_set) = bits_are_on;
(*bits_not_set) = bits_are_off;
}

int main()
{
int number = 0;
unsigned int bits_on = 0, bits_off = 0;

printf("Counting the bits!\n");
printf("Please enter a integer value: ");
scanf("%d", & number);
printf("\nThe value was: %d\n", number);

tallybin(number, &bits_on, &bits_off);

printf("\nNumber of bits are set: %u\n", bits_on);
printf("Number of bits not set: %u\n", bits_off);

return 0;
}```
Hey Mister Tallyman telly me banana........... 3. Originally Posted by akis OK I solved it.
There is an alternative method, but it requires a bit of insight to sum up bit fields in parallel.

Code:
```    #include <stdio.h>
int main()
{
int x ;
printf("Enter number: ");
scanf("%d",&x);
x = (x & 0xaa) >> 1;
x = (x >> 4) + (x & 0xf);
x = (x >> 2) + (x & 0x3);
printf("sum: %d\n", x);
return 0;
}``` Popular pages Recent additions binary, bit-shift, bitwise-operators, positions, program 