PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

number to bitshift

Is there any one line math thingie one can do to convert a number such as 2, 16, 64 or 2048 into a bitshift value? So like if I have 1024 and do this thing on it it will return 10 (since 1 << 10 = 1024).

Guess this is really simple, but I'm too lazy to think... ;)
angedelamort · 09 Oct 2002, 16:18 UTC
The only thing I can think that will not add overhead to your code is to define some constant lol

Code:

#define BIN_SHIFT_1024 10


But I don't see why you want to do that... Using a function to transform will add more overhead than just writing 1 * 1024 lol
My maths isn't wonderful so there might be a better method:

log(number)/log(2)

e.g.

log(1024)/log(2) = 10
This any good?

Code:

int n=1024;
int i=0;
for (i=0;i<32;i++) { n>>=1; if (n==0) break; }
If you're running on XScale you can use CLZ, then subtract the result from 31.

Otherwise, I'd probably perform a series of AND operations with mask and use a divide-and-conquer approach to find the set bit (test HIWORD/LOWORD, test HIBYTE/LOBYTE, test HINIBBLE/LONIBBLE, etc.). This will get you the result after 5 ANDs and 5 comparisons. It's not one line of code, but it's probably faster than the other methods suggested.
If we're ignoring the one-line thing, I love this one (not because of its efficiency because it's less efficient than the divide-and-conquer Digby suggested and will be less efficient than the CLZ.. but it's just evil :D ):

(comp.sys.arm has lots of useful ARM tips like this - this isn't my article or code).
Code:

/*
From: Richard Woodruff <richardw@microware.com>
Newsgroups: comp.sys.arm
Subject: Re: Finding highest/lowest set bit
Date: 28 Oct 2000 01:01:26 GMT

This in a bit differnt syntax was posted a while
back by someone.

Richard W.
*/

#include <types.h>

u_int32 clz(u_int32 n);

const char clz_table[32] = {
0, 31, 9, 30, 3, 8, 18, 29, 2, 5, 7, 14, 12, 17,
22, 28, 1, 10, 4, 19, 6, 15, 13, 23, 11, 20, 16,
24, 21, 25, 26, 27 };

u_int32 clz(u_int32 n)
{
u_int32 c = 0x7dcd629; /* magic constant... */

n |= (n >> 1);
n |= (n >> 2);
n |= (n >> 4);
n |= (n >> 8);
n |= (n >> 16);
if (n == 0) return 32;
n = c + (c * n);
#ifndef _X86_ //Big-Endian
return clz_table[n >> 27];
#else //Little-Endian
return 31-clz_table[n >> 27];
#endif
}

main()
{
u_int32 val = 0x10000000;
u_int32 val2 =0x00001000;
u_int32 val3 =0x80000000;

printf(" val is %d\n",clz(val));
printf(" val is %d\n",clz(val2));
printf(" val is %d\n",clz(val3));
}


[Modified by Dan East for Little-Endian]
I will only be running this when initing the app, so it really doesn't matter if it is nice code or not. Actually I really don't need it that bad. Was mostly curious if there was some obvious thing that I'd missed. This is the style I do now:

Code:

int a = 1; // Will contain the result
int b = 4096; // Number to "convert"
while((b >>= 1) != 1) a++;
I would say refractor's is the cleanest.
I hope b is never zero. :D
If it is the software will create a huge disruption in space time continuum, which will lead to the ultimate destruction of the universe and everything in it, except for the duracell bunny. It keeps going and going forever and ever...

...Or maybe not...
Here's another potential issue - what happens if b is negative?

As it's signed, the shift will be arithmetic, thus it'll end up as -1, never 1... giving us the infinite loop until the bunny's batteries run out ;)
What if the bunny is connected to a 12V adaptor...then we have serious issues with the world collapsing and stuff...
Your forgetting all about the Bunny factor D, which states that to sucessfully power a bunny, you will need a cold fusion reactor, so keeping the bunny powered after the break is merely a dream.
Ouch forgot that...so the problem will basically cause the entire universe to collapse, and that's it...?

maybe I should run my app in debug mode first, so I can catch the exception before the world is destroyed.
Has anyone tried the code Refractor posted? I can't get it to return proper results.

Dan East
Stepping through the code:

Code:

//param n=4096
u_int32 c = 0x7dcd629; /* magic constant... */

n |= (n >> 1);
//n=6144
n |= (n >> 2);
//n=7680
n |= (n >> 4);
//n=8160
n |= (n >> 8);
//n=8191
n |= (n >> 16);
//n=8191
if (n == 0) return 32;
n = c + (c * n);
//n=0x9ac52000
return clz_table[n >> 27];
//n>>27 = 19
//clz_table[19] = 19
//returns 19


Dan East
Ahhh. This code is designed for big-endian processors. I'm testing on x86, which is little-endian. For little endian you can reorder the table, or change the last line to:
return 31-clz_table[n >> 27];

Dan East
Just nitpicking here, but I would move the test for n being equal to zero to the head of that function.

I benchmarked this code against a binary search implemenation on an X86 machine. The binary search was slightly faster, but nothing to write home about (140ms over 50M calls).
Just for the hell of it, here's a template metaprogramming way to do it and get everything at compile time :D

(little endian of course...)

Code:

template <int I>
class ShiftCount {
public:
enum { Result = 1 + ShiftCount<I >> 1>::Result };
};

class ShiftCount<1> {
public:
enum { Result = 0 };
};

class ShiftCount<0> {
public:
enum { Result = 0 };
};


So ShiftCount<2048>::Result will give you 10, etc.
Here's a difference approach.

Code:

unsigned number;
int bit = 31;
while(!((1 << bit) & number))
bit--;


Comparison:
Original:
shift, assign, compare to one
New:
shift, binary-and, compare to zero


Malmer wrote:
Code:

int a = 1; // Will contain the result
int b = 4096; // Number to "convert"
while((b >>= 1) != 1) a++;




Just out of interest (and I can't think of any reason to need this) what do you need to do this for?
Sm!rk wrote:
Just out of interest (and I can't think of any reason to need this) what do you need to do this for?


In Varium a number is shifted right by a user-supplied value (can't divide due to performance). In the config file instead of requiring the user to specify a shift value, they can specify the actual numeric value. So they get to express in familar world units, instead of providing something more abstract like an exponent.

However, I'm thinking of using something different. If the user supplies 4095, it would be better to round up to 4096, so the exponent is 12. The routines listed above would all return the highest bit 11, giving a result 50% less then desired.

Dan East
Geez, if it's in the config file can't you simply using floating point calcs to come up with your power-of-two divisor instead of all that clz hocus pocus? How often are they setting this value?
Dan East wrote:
However, I'm thinking of using something different. If the user supplies 4095, it would be better to round up to 4096, so the exponent is 12. The routines listed above would all return the highest bit 11, giving a result 50% less then desired.


Well, it's not that they don't work, it's just that you need to round the power of two beforehand.
For example -
Code:

int CeilPW2(int val) {
val-=1;
int i = 1;
while (i <= 32) {
val|=(val >> i);
i<<=1;
}
return val + 1;
}

int ShiftCount(const int val) {
int bit = 1;
while(!((1 << bit) & val)) {
++bit;
}
return bit;
}
So, ShiftCount(CeilPW2(4095)) == 12 as you wanted.
/me just looks at the posts, jaw dropped..... and thinks to himself "ahh to have the time avaliable in my life again to ponder the affects my lose coding will have on the universe"

;-)