Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
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 unsigned int __sw_hweight32(unsigned int w)
0013 {
0014 #ifdef CONFIG_ARCH_HAS_FAST_MULTIPLIER
0015     w -= (w >> 1) & 0x55555555;
0016     w =  (w & 0x33333333) + ((w >> 2) & 0x33333333);
0017     w =  (w + (w >> 4)) & 0x0f0f0f0f;
0018     return (w * 0x01010101) >> 24;
0019 #else
0020     unsigned int res = w - ((w >> 1) & 0x55555555);
0021     res = (res & 0x33333333) + ((res >> 2) & 0x33333333);
0022     res = (res + (res >> 4)) & 0x0F0F0F0F;
0023     res = res + (res >> 8);
0024     return (res + (res >> 16)) & 0x000000FF;
0025 #endif
0026 }
0027 
0028 unsigned int __sw_hweight16(unsigned int w)
0029 {
0030     unsigned int res = w - ((w >> 1) & 0x5555);
0031     res = (res & 0x3333) + ((res >> 2) & 0x3333);
0032     res = (res + (res >> 4)) & 0x0F0F;
0033     return (res + (res >> 8)) & 0x00FF;
0034 }
0035 
0036 unsigned int __sw_hweight8(unsigned int w)
0037 {
0038     unsigned int res = w - ((w >> 1) & 0x55);
0039     res = (res & 0x33) + ((res >> 2) & 0x33);
0040     return (res + (res >> 4)) & 0x0F;
0041 }
0042 
0043 unsigned long __sw_hweight64(__u64 w)
0044 {
0045 #if BITS_PER_LONG == 32
0046     return __sw_hweight32((unsigned int)(w >> 32)) +
0047            __sw_hweight32((unsigned int)w);
0048 #elif BITS_PER_LONG == 64
0049 #ifdef CONFIG_ARCH_HAS_FAST_MULTIPLIER
0050     w -= (w >> 1) & 0x5555555555555555ul;
0051     w =  (w & 0x3333333333333333ul) + ((w >> 2) & 0x3333333333333333ul);
0052     w =  (w + (w >> 4)) & 0x0f0f0f0f0f0f0f0ful;
0053     return (w * 0x0101010101010101ul) >> 56;
0054 #else
0055     __u64 res = w - ((w >> 1) & 0x5555555555555555ul);
0056     res = (res & 0x3333333333333333ul) + ((res >> 2) & 0x3333333333333333ul);
0057     res = (res + (res >> 4)) & 0x0F0F0F0F0F0F0F0Ful;
0058     res = res + (res >> 8);
0059     res = res + (res >> 16);
0060     return (res + (res >> 32)) & 0x00000000000000FFul;
0061 #endif
0062 #endif
0063 }