I’m trying a basic Hash-Table program..which is to count number of 1’s in an integer:
I have a hash-table which is an array with number of 1’s in 0,1,2...E,F
HashTable:
0 0
1 1
2 1
3 2
4 1
5 1
6 2
7 3
8 1
9 2
A 2
B 3
C 2
D 3
E 3
F 4
Now, I want to extract 8 nibbles from integer so that I can use arr[nibble-value] to get number of 1’s in each nibble.
int arr[16] = {0,1,1,2,1,1,2,3,1,2,2,3,2,3,3,4};
int main (void)
{
int x = 127;
int temp, sum =0, i;
int nibbles = 2 * sizeof(x);
for (i = 1; i<= nibbles; i++)
{
temp = x << (4*i); // <<< I Know this is wrong!!!! <<Here is what I need!!>>
printf("Temp[%d]:%d\n", i, temp);
sum = sum + arr[temp];
}
printf("No.of ones: %d\n", sum);
return 0;
}
May be a simple logic…
Remember that the first bit is numbered zero, and so is the first nibble, exactly like array indexes. So by starting the loop from
1you actually start with the second nibble and get the last nibble from beyond the integer.Also, you shift in the wrong direction, and should mask out the top bits, i.e. do