blob: 4382576717086eeaaa48d928db67dfb6757cbbb7 [file] [log] [blame]
Akinobu Mita3b9ed1a2006-03-26 01:39:13 -08001#include <linux/module.h>
2#include <asm/types.h>
3
4/**
5 * hweightN - returns the hamming weight of a N-bit word
6 * @x: the word to weigh
7 *
8 * The Hamming Weight of a number is the total number of bits set in it.
9 */
10
11unsigned int hweight32(unsigned int w)
12{
Akinobu Mitaf9b41922006-03-26 01:40:00 -080013 unsigned int res = w - ((w >> 1) & 0x55555555);
Akinobu Mita3b9ed1a2006-03-26 01:39:13 -080014 res = (res & 0x33333333) + ((res >> 2) & 0x33333333);
Akinobu Mitaf9b41922006-03-26 01:40:00 -080015 res = (res + (res >> 4)) & 0x0F0F0F0F;
16 res = res + (res >> 8);
17 return (res + (res >> 16)) & 0x000000FF;
Akinobu Mita3b9ed1a2006-03-26 01:39:13 -080018}
19EXPORT_SYMBOL(hweight32);
20
21unsigned int hweight16(unsigned int w)
22{
Akinobu Mitaf9b41922006-03-26 01:40:00 -080023 unsigned int res = w - ((w >> 1) & 0x5555);
Akinobu Mita3b9ed1a2006-03-26 01:39:13 -080024 res = (res & 0x3333) + ((res >> 2) & 0x3333);
Akinobu Mitaf9b41922006-03-26 01:40:00 -080025 res = (res + (res >> 4)) & 0x0F0F;
26 return (res + (res >> 8)) & 0x00FF;
Akinobu Mita3b9ed1a2006-03-26 01:39:13 -080027}
28EXPORT_SYMBOL(hweight16);
29
30unsigned int hweight8(unsigned int w)
31{
Akinobu Mitaf9b41922006-03-26 01:40:00 -080032 unsigned int res = w - ((w >> 1) & 0x55);
Akinobu Mita3b9ed1a2006-03-26 01:39:13 -080033 res = (res & 0x33) + ((res >> 2) & 0x33);
Akinobu Mitaf9b41922006-03-26 01:40:00 -080034 return (res + (res >> 4)) & 0x0F;
Akinobu Mita3b9ed1a2006-03-26 01:39:13 -080035}
36EXPORT_SYMBOL(hweight8);
37
38unsigned long hweight64(__u64 w)
39{
40#if BITS_PER_LONG == 32
41 return hweight32((unsigned int)(w >> 32)) + hweight32((unsigned int)w);
42#elif BITS_PER_LONG == 64
Akinobu Mitaf9b41922006-03-26 01:40:00 -080043 __u64 res = w - ((w >> 1) & 0x5555555555555555ul);
Akinobu Mita3b9ed1a2006-03-26 01:39:13 -080044 res = (res & 0x3333333333333333ul) + ((res >> 2) & 0x3333333333333333ul);
Akinobu Mitaf9b41922006-03-26 01:40:00 -080045 res = (res + (res >> 4)) & 0x0F0F0F0F0F0F0F0Ful;
46 res = res + (res >> 8);
47 res = res + (res >> 16);
48 return (res + (res >> 32)) & 0x00000000000000FFul;
Akinobu Mita3b9ed1a2006-03-26 01:39:13 -080049#else
50#error BITS_PER_LONG not defined
51#endif
52}
53EXPORT_SYMBOL(hweight64);