Here is a speed optimized version:
#include <stdio.h>
int calculate_1 (unsigned char byte)
{
const unsigned char checktable[16]={0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4};
return checktable[byte&0x0F] + checktable[byte>>4];
}
int main (void)
{
unsigned char data[5] = {0x01, 0x02, 0x04, 0x0F, 0xAA}; // 11
unsigned char sum=0;
unsigned char i;
for(i=0; i<5; i++)
sum += calculate_1(data[i]);
printf("%d",sum);
getchar();
return 0;
}
If you need to use other types than char, typecast them and run the function for each byte:
int data = 0xF00F00;
unsigned char sum=0;
unsigned char i;
for(i=0; i<sizeof(data); i++)
{
unsigned char* chp = (unsigned char*)&data;
sum += calculate_1(chp[i]);
}