Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 #include <linux/export.h>
0003 #include <linux/bitops.h>
0004 #include <asm/types.h>
0005 
0006 /**
0007  * hweightN - returns the hamming weight of a N-bit word
0008  * @x: the word to weigh
0009  *
0010  * The Hamming Weight of a number is the total number of bits set in it.
0011  */
0012 
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 
0030 unsigned int __sw_hweight16(unsigned int w)
0031 {
0032     unsigned int res = w - ((w >> 1) & 0x5555);
0033     res = (res & 0x3333) + ((res >> 2) & 0x3333);
0034     res = (res + (res >> 4)) & 0x0F0F;
0035     return (res + (res >> 8)) & 0x00FF;
0036 }
0037 EXPORT_SYMBOL(__sw_hweight16);
0038 
0039 unsigned int __sw_hweight8(unsigned int w)
0040 {
0041     unsigned int res = w - ((w >> 1) & 0x55);
0042     res = (res & 0x33) + ((res >> 2) & 0x33);
0043     return (res + (res >> 4)) & 0x0F;
0044 }
0045 EXPORT_SYMBOL(__sw_hweight8);
0046 
0047 unsigned long __sw_hweight64(__u64 w)
0048 {
0049 #if BITS_PER_LONG == 32
0050     return __sw_hweight32((unsigned int)(w >> 32)) +
0051            __sw_hweight32((unsigned int)w);
0052 #elif BITS_PER_LONG == 64
0053 #ifdef CONFIG_ARCH_HAS_FAST_MULTIPLIER
0054     w -= (w >> 1) & 0x5555555555555555ul;
0055     w =  (w & 0x3333333333333333ul) + ((w >> 2) & 0x3333333333333333ul);
0056     w =  (w + (w >> 4)) & 0x0f0f0f0f0f0f0f0ful;
0057     return (w * 0x0101010101010101ul) >> 56;
0058 #else
0059     __u64 res = w - ((w >> 1) & 0x5555555555555555ul);
0060     res = (res & 0x3333333333333333ul) + ((res >> 2) & 0x3333333333333333ul);
0061     res = (res + (res >> 4)) & 0x0F0F0F0F0F0F0F0Ful;
0062     res = res + (res >> 8);
0063     res = res + (res >> 16);
0064     return (res + (res >> 32)) & 0x00000000000000FFul;
0065 #endif
0066 #endif
0067 }
0068 EXPORT_SYMBOL(__sw_hweight64);