]> git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blame - lib/hweight.c
UBUNTU: Ubuntu-4.15.0-96.97
[mirror_ubuntu-bionic-kernel.git] / lib / hweight.c
CommitLineData
b2441318 1// SPDX-License-Identifier: GPL-2.0
8bc3bcc9 2#include <linux/export.h>
1977f032 3#include <linux/bitops.h>
3b9ed1a5
AM
4#include <asm/types.h>
5
6/**
7 * hweightN - returns the hamming weight of a N-bit word
8 * @x: the word to weigh
9 *
10 * The Hamming Weight of a number is the total number of bits set in it.
11 */
12
f5967101 13#ifndef __HAVE_ARCH_SW_HWEIGHT
d61931d8 14unsigned int __sw_hweight32(unsigned int w)
3b9ed1a5 15{
72d93104 16#ifdef CONFIG_ARCH_HAS_FAST_MULTIPLIER
39d997b5
AM
17 w -= (w >> 1) & 0x55555555;
18 w = (w & 0x33333333) + ((w >> 2) & 0x33333333);
19 w = (w + (w >> 4)) & 0x0f0f0f0f;
20 return (w * 0x01010101) >> 24;
21#else
f9b41929 22 unsigned int res = w - ((w >> 1) & 0x55555555);
3b9ed1a5 23 res = (res & 0x33333333) + ((res >> 2) & 0x33333333);
f9b41929
AM
24 res = (res + (res >> 4)) & 0x0F0F0F0F;
25 res = res + (res >> 8);
26 return (res + (res >> 16)) & 0x000000FF;
39d997b5 27#endif
3b9ed1a5 28}
d61931d8 29EXPORT_SYMBOL(__sw_hweight32);
f5967101 30#endif
3b9ed1a5 31
d61931d8 32unsigned int __sw_hweight16(unsigned int w)
3b9ed1a5 33{
f9b41929 34 unsigned int res = w - ((w >> 1) & 0x5555);
3b9ed1a5 35 res = (res & 0x3333) + ((res >> 2) & 0x3333);
f9b41929
AM
36 res = (res + (res >> 4)) & 0x0F0F;
37 return (res + (res >> 8)) & 0x00FF;
3b9ed1a5 38}
d61931d8 39EXPORT_SYMBOL(__sw_hweight16);
3b9ed1a5 40
d61931d8 41unsigned int __sw_hweight8(unsigned int w)
3b9ed1a5 42{
f9b41929 43 unsigned int res = w - ((w >> 1) & 0x55);
3b9ed1a5 44 res = (res & 0x33) + ((res >> 2) & 0x33);
f9b41929 45 return (res + (res >> 4)) & 0x0F;
3b9ed1a5 46}
d61931d8 47EXPORT_SYMBOL(__sw_hweight8);
3b9ed1a5 48
f5967101 49#ifndef __HAVE_ARCH_SW_HWEIGHT
d61931d8 50unsigned long __sw_hweight64(__u64 w)
3b9ed1a5
AM
51{
52#if BITS_PER_LONG == 32
d61931d8
BP
53 return __sw_hweight32((unsigned int)(w >> 32)) +
54 __sw_hweight32((unsigned int)w);
3b9ed1a5 55#elif BITS_PER_LONG == 64
72d93104 56#ifdef CONFIG_ARCH_HAS_FAST_MULTIPLIER
0136611c
AK
57 w -= (w >> 1) & 0x5555555555555555ul;
58 w = (w & 0x3333333333333333ul) + ((w >> 2) & 0x3333333333333333ul);
59 w = (w + (w >> 4)) & 0x0f0f0f0f0f0f0f0ful;
60 return (w * 0x0101010101010101ul) >> 56;
61#else
f9b41929 62 __u64 res = w - ((w >> 1) & 0x5555555555555555ul);
3b9ed1a5 63 res = (res & 0x3333333333333333ul) + ((res >> 2) & 0x3333333333333333ul);
f9b41929
AM
64 res = (res + (res >> 4)) & 0x0F0F0F0F0F0F0F0Ful;
65 res = res + (res >> 8);
66 res = res + (res >> 16);
67 return (res + (res >> 32)) & 0x00000000000000FFul;
0136611c 68#endif
3b9ed1a5
AM
69#endif
70}
d61931d8 71EXPORT_SYMBOL(__sw_hweight64);
f5967101 72#endif