Welcome to little lamb

Code » test-msb » next » tree

[next] / src / m4.c

#include <stdint.h>

typedef uint64_t u64;

/* Kaz Kylheku */

int msb(u64 v)
{
  const long long mask[] = {
    0x00000000FFFFFFFF,
    0x000000000000FFFF,
    0x00000000000000FF,
    0x000000000000000F,
    0x0000000000000003,
    0x0000000000000001
  };
  int hi = 64;
  int lo = 0;
  int i = 0;

  if (v == 0)
    return 0;

  for (i = 0; i < sizeof mask / sizeof mask[0]; i++) {
    int mi = lo + (hi - lo) / 2;

    if ((v >> mi) != 0)
      lo = mi;
    else if ((v & (mask[i] << lo)) != 0)
      hi = mi;
  }

  return lo + 1;
}