haiku/headers/private/kernel/util/BitUtils.h

61 lines
1.1 KiB
C
Raw Normal View History

2013-10-02 23:24:46 +04:00
/*
* Copyright 2013 Haiku, Inc. All rights reserved.
* Distributed under the terms of the MIT License.
*
* Authors:
* Paweł Dziepak, pdziepak@quarnos.org
*/
#ifndef KERNEL_UTIL_BITUTIL_H
#define KERNEL_UTIL_BITUTIL_H
#include <SupportDefs.h>
// http://graphics.stanford.edu/~seander/bithacks.html
static inline uint32
2013-10-05 20:03:00 +04:00
next_power_of_2(uint32 v)
2013-10-02 23:24:46 +04:00
{
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;
}
// http://graphics.stanford.edu/~seander/bithacks.html
static inline uint32
2013-10-05 20:03:00 +04:00
count_set_bits(uint32 v)
2013-10-02 23:24:46 +04:00
{
v = v - ((v >> 1) & 0x55555555);
v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
return (((v + (v >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24;
}
2013-10-03 06:27:49 +04:00
static inline uint32
log2(uint32 v)
{
static const int MultiplyDeBruijnBitPosition[32] = {
0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30,
8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31
};
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
return MultiplyDeBruijnBitPosition[(uint32)(v * 0x07C4ACDDU) >> 27];
}
#endif // KERNEL_UTIL_BITUTIL_H
2013-10-02 23:24:46 +04:00