Back to home page

LXR

 
 

    


0001 #include <linux/export.h>
0002 #include <linux/bitops.h>
0003 #include <asm/types.h>
0004 
0005 /**
0006  * hweightN - returns the hamming weight of a N-bit word
0007  * @x: the word to weigh
0008  *
0009  * The Hamming Weight of a number is the total number of bits set in it.
0010  */
0011 
0012 #ifndef __HAVE_ARCH_SW_HWEIGHT
0013 unsigned int __sw_hweight32(unsigned int w)
0014 {
0015 #ifdef CONFIG_ARCH_HAS_FAST_MULTIPLIER
0016     w -= (w >> 1) & 0x55555555;
0017     w =  (w & 0x33333333) + ((w >> 2) & 0x33333333);
0018     w =  (w + (w >> 4)) & 0x0f0f0f0f;
0019     return (w * 0x01010101) >> 24;
0020 #else
0021     unsigned int res = w - ((w >> 1) & 0x55555555);
0022     res = (res & 0x33333333) + ((res >> 2) & 0x33333333);
0023     res = (res + (res >> 4)) & 0x0F0F0F0F;
0024     res = res + (res >> 8);
0025     return (res + (res >> 16)) & 0x000000FF;
0026 #endif
0027 }
0028 EXPORT_SYMBOL(__sw_hweight32);
0029 #endif
0030 
0031 unsigned int __sw_hweight16(unsigned int w)
0032 {
0033     unsigned int res = w - ((w >> 1) & 0x5555);
0034     res = (res & 0x3333) + ((res >> 2) & 0x3333);
0035     res = (res + (res >> 4)) & 0x0F0F;
0036     return (res + (res >> 8)) & 0x00FF;
0037 }
0038 EXPORT_SYMBOL(__sw_hweight16);
0039 
0040 unsigned int __sw_hweight8(unsigned int w)
0041 {
0042     unsigned int res = w - ((w >> 1) & 0x55);
0043     res = (res & 0x33) + ((res >> 2) & 0x33);
0044     return (res + (res >> 4)) & 0x0F;
0045 }
0046 EXPORT_SYMBOL(__sw_hweight8);
0047 
0048 #ifndef __HAVE_ARCH_SW_HWEIGHT
0049 unsigned long __sw_hweight64(__u64 w)
0050 {
0051 #if BITS_PER_LONG == 32
0052     return __sw_hweight32((unsigned int)(w >> 32)) +
0053            __sw_hweight32((unsigned int)w);
0054 #elif BITS_PER_LONG == 64
0055 #ifdef CONFIG_ARCH_HAS_FAST_MULTIPLIER
0056     w -= (w >> 1) & 0x5555555555555555ul;
0057     w =  (w & 0x3333333333333333ul) + ((w >> 2) & 0x3333333333333333ul);
0058     w =  (w + (w >> 4)) & 0x0f0f0f0f0f0f0f0ful;
0059     return (w * 0x0101010101010101ul) >> 56;
0060 #else
0061     __u64 res = w - ((w >> 1) & 0x5555555555555555ul);
0062     res = (res & 0x3333333333333333ul) + ((res >> 2) & 0x3333333333333333ul);
0063     res = (res + (res >> 4)) & 0x0F0F0F0F0F0F0F0Ful;
0064     res = res + (res >> 8);
0065     res = res + (res >> 16);
0066     return (res + (res >> 32)) & 0x00000000000000FFul;
0067 #endif
0068 #endif
0069 }
0070 EXPORT_SYMBOL(__sw_hweight64);
0071 #endif