Skip to content
Snippets Groups Projects
bitlog.cpp 1.56 KiB
#include "wrap_cl.h"
#include "function.h"

#include <climits>
#include <stdint.h>

/* from http://graphics.stanford.edu/~seander/bithacks.html */
static const char log_table_8[] = {
    0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3,
    4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
    5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
    5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
    6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
    6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
    6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
    6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
    7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
    7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
    7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
    7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
    7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
    7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
    7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
    7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7
};

static PYOPENCL_INLINE unsigned
bitlog2_16(uint16_t v)
{
    if (unsigned long t = v >> 8) {
        return 8 + log_table_8[t];
    } else {
        return log_table_8[v];
    }
}

static PYOPENCL_INLINE unsigned
bitlog2_32(uint32_t v)
{
    if (uint16_t t = v >> 16) {
        return 16 + bitlog2_16(t);
    } else {
      return bitlog2_16(v);
    }
}

unsigned
bitlog2(unsigned long v)
{
#if (ULONG_MAX != 4294967295)
    if (uint32_t t = v >> 32) {
        return 32 + bitlog2_32(t);
    } else {
#endif
        return bitlog2_32(v);
#if (ULONG_MAX != 4294967295)
    }
#endif
}