473,402 Members | 2,053 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,402 software developers and data experts.

bit position

What would be an optimal way to get the position of the lowest bit where you
know only 1 bit will be on 1?
Like in the position of bit 0x8 is 4, 0x4 it's 3 etc.

Best thing I could come up with is

#define BITPOS(x) \

((x) & 0x1 ? 1 : \

(x) & 0x2 ? 2 : \

(x) & 0x4 ? 3 : \

(x) & 0x8 ? 4 : 0)

int main(void) {

unsigned short x = 0x0008;

while (x) {

printf("%d\n", BITPOS(x));

x >>= 4;

}
return 0;

}
Oct 25 '06 #1
12 3697
Serve Laurijssen said:
What would be an optimal way to get the position of the lowest bit where
you know only 1 bit will be on 1?
If you have an n-bit unsigned integer type, start off by comparing the value
with (1 << (n / 2)), and home in on the bit using binary search, for O(log
n) instead of O(n).

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Oct 25 '06 #2

"Serve Laurijssen" <se*@n.tkha scritto nel messaggio
news:eh**********@news5.zwoll1.ov.home.nl...
What would be an optimal way to get the position of the lowest bit where
you
know only 1 bit will be on 1?
Like in the position of bit 0x8 is 4, 0x4 it's 3 etc.

Best thing I could come up with is

#define BITPOS(x) \

((x) & 0x1 ? 1 : \

(x) & 0x2 ? 2 : \

(x) & 0x4 ? 3 : \

(x) & 0x8 ? 4 : 0)

int main(void) {

unsigned short x = 0x0008;

while (x) {

printf("%d\n", BITPOS(x));

x >>= 4;

}
return 0;

}
Another possibility is a 'look-up table':

/*
* for nibbles: position of 'lowest 1', (0 if missing)
*/
int bitpos[] = {
0, /* 0 0 0 0 */
1, /* 0 0 0 1 */
2, /* 0 0 1 0 */
1, /* 0 0 1 1 */
3, /* 0 1 0 0 */
1, /* 0 1 0 1 */
2, /* 0 1 1 0 */
1, /* 0 1 1 1 */
4, /* 1 0 0 0 */
1, /* 1 0 0 1 */
2, /* 1 0 1 0 */
1, /* 1 0 1 1 */
3, /* 1 1 0 0 */
1, /* 1 1 0 1 */
2, /* 1 1 1 0 */
1, /* 1 1 1 1 */
};

/*
* usage
*/
bitp = bitpos[0xF & x];

--
Giorgio Silvestri
DSP/Embedded/Real Time OS Software Engineer

Oct 25 '06 #3

"Serve Laurijssen" <se*@n.tkwrote in message
news:eh**********@news5.zwoll1.ov.home.nl...
What would be an optimal way to get the position of the lowest bit where
you know only 1 bit will be on 1?
Like in the position of bit 0x8 is 4, 0x4 it's 3 etc.
so there isnt some bid fiddle solution to this? :)
Oct 25 '06 #4


Serve Laurijssen wrote On 10/25/06 17:27,:
"Serve Laurijssen" <se*@n.tkwrote in message
news:eh**********@news5.zwoll1.ov.home.nl...
>>What would be an optimal way to get the position of the lowest bit where
you know only 1 bit will be on 1?
Like in the position of bit 0x8 is 4, 0x4 it's 3 etc.


so there isnt some bid fiddle solution to this? :)
One trick that's sometimes used is to convert the value
to floating-point and then look at the exponent:

#include <math.h>
int bitpos(unsigned long one_bit_is_set) {
int exponent;
(void) frexp(one_bit_is_set, &exponent);
return exponent - 1;
}

.... but whether this counts as "optimal" is open to question.
Usually, this trick is used along with a bunch of non-portable
knowledge about the machine's floating-point hardware instead
of relying on the portable frexp() function. Even with such
knowledge, some machines may not perform well if there's too
much cross-talk between the integer and F-P componentry.

--
Er*********@sun.com

Oct 25 '06 #5


Eric Sosman wrote On 10/25/06 17:46,:
>
Serve Laurijssen wrote On 10/25/06 17:27,:
>>"Serve Laurijssen" <se*@n.tkwrote in message
news:eh**********@news5.zwoll1.ov.home.nl...

>>>What would be an optimal way to get the position of the lowest bit where
you know only 1 bit will be on 1?
Like in the position of bit 0x8 is 4, 0x4 it's 3 etc.


so there isnt some bid fiddle solution to this? :)


One trick that's sometimes used is to convert the value
to floating-point and then look at the exponent:

#include <math.h>
int bitpos(unsigned long one_bit_is_set) {
int exponent;
(void) frexp(one_bit_is_set, &exponent);
return exponent - 1;
Just noticed that this returns the more usual bit
numbering: 1->0, 8->3, 32->5 and so on. For the off-
by-one numbering you asked for, just return `exponent'
and omit the `- 1'.

--
Er*********@sun.com

Oct 25 '06 #6

Serve Laurijssen wrote:
What would be an optimal way to get the position of the lowest bit where you
know only 1 bit will be on 1?
Optimal in terms of size or execution speed? and then again it is
dependent on the processor you are working on. Usual method is, shift
the number by one and compare with zero, other alternatives includes
look up tables (at increased cost of size), use of special instructions
to count the leading zeros and so on...

-Nishu

Oct 26 '06 #7
Ico
Serve Laurijssen <se*@n.tkwrote:
What would be an optimal way to get the position of the lowest bit where you
know only 1 bit will be on 1?
Like in the position of bit 0x8 is 4, 0x4 it's 3 etc.

Best thing I could come up with is

#define BITPOS(x) \

((x) & 0x1 ? 1 : \
(x) & 0x2 ? 2 : \
(x) & 0x4 ? 3 : \
(x) & 0x8 ? 4 : 0)

There are a number of recipes for this problem in the book 'Hackers
Delight'. A lot depends on the type of CPU you are using, and if you
want fast execution or small code size.

This is a basic binary search technique : [code fragments from Hackers
Delight]

if (x == 0) return(32);
n = 0;
if (x <= 0x0000FFFF) {n = n +16; x = x <<16;}
if (x <= 0x00FFFFFF) {n = n + 8; x = x << 8;}
if (x <= 0x0FFFFFFF) {n = n + 4; x = x << 4;}
if (x <= 0x3FFFFFFF) {n = n + 2; x = x << 2;}
if (x <= 0x7FFFFFFF) {n = n + 1;}
return n;

Or the other way around, counting down:

int nlz(unsigned x)
{
unsigned y;
int n;

n = 32;
y = x >>16; if (y != 0) {n = n -16; x = y;}
y = x >8; if (y != 0) {n = n - 8; x = y;}
y = x >4; if (y != 0) {n = n - 4; x = y;}
y = x >2; if (y != 0) {n = n - 2; x = y;}
y = x >1; if (y != 0) return n - 2;
return n - x;
}
If you prefer speed over code size, a table lookup would probably be the
fastest solution:

static char table[256] = {0,1,2,2,3,3,3,3,4,4,...,8);
return n - table[x];
--
:wq
^X^Cy^K^X^C^C^C^C
Oct 26 '06 #8
Serve Laurijssen writes:
What would be an optimal way to get the position of the lowest bit
where you know only 1 bit will be on 1?
Possibly the POSIX ffs() function in <string.h>. Or if the value is
an 8-bit byte, you could use 7 - 86/(val + 11). Don't know how they
compare with some of the other methods in this thread, though.

--
Hallvard
Oct 26 '06 #9
Hallvard B Furuseth <h.**********@usit.uio.nowrites:
Serve Laurijssen writes:
>What would be an optimal way to get the position of the lowest bit
where you know only 1 bit will be on 1?

Possibly the POSIX ffs() function in <string.h>.
[...]

<OT>
ffs() is not declared in <string.h>. Consult your documentation for
more information, or try comp.unix.programmer.
</OT>

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Oct 26 '06 #10
Keith Thompson <ks***@mib.orgwrites:
Hallvard B Furuseth <h.**********@usit.uio.nowrites:
>Serve Laurijssen writes:
>>What would be an optimal way to get the position of the lowest bit
where you know only 1 bit will be on 1?

Possibly the POSIX ffs() function in <string.h>.
[...]

<OT>
ffs() is not declared in <string.h>.
Oops - <strings.h>.
Consult your documentation for more information,
I did, and misread. I know strings.h isn't used anymore, right?:-)
or try comp.unix.programmer.
--
Hallvard
Oct 26 '06 #11
Serve Laurijssen wrote:
"Serve Laurijssen" <se*@n.tkwrote in message
news:eh**********@news5.zwoll1.ov.home.nl...
>What would be an optimal way to get the position of the lowest bit where
you know only 1 bit will be on 1?
Like in the position of bit 0x8 is 4, 0x4 it's 3 etc.

so there isnt some bid fiddle solution to this? :)
Well you can take Richard's suggestion and code it as a binary search:

int lowest_bit_pos(unsigned long long v)
{
int top = CHAR_BIT * sizeof(unsigned long long);
int bot = 0;
int a = (top + bot) / 2;
unsigned long long tv = 1ULL << a;
while(v != tv)
{
if(top == bot || top == bot + 1) return -1; /* 0 or >1 bits set */
if(v < tv) top = a; else bot = a;
a = (top + bot) / 2;
tv = 1ULL << a;
}
return a;
}

Or you could just use floating-point maths:

int lowest_bit_pos(unsigned long long v)
{
return round(log(v) / log(2));
}

--
Simon.
Oct 26 '06 #12
On Wed, 25 Oct 2006 19:17:42 +0200, "Serve Laurijssen" <se*@n.tk>
wrote:
What would be an optimal way to get the position of the lowest bit where you
know only 1 bit will be on 1?
Like in the position of bit 0x8 is 4, 0x4 it's 3 etc.
A mathematically clever way is to choose an integer N not much larger
than the width of your input values such that the multiplicative group
Z_n^* is generated by 2, and precompute (at build time or process
startup) the discrete log2 table; then given a value P with only one
bit set hence a power of two, P % N is a unique value and looking it
up in your table gives the answer. For example for 32 bits use 37.

However, general % is implemented using a divide operation and
possibly a multiply, or at best two chained multiplies, and on most if
not all modern computers that is slower than the bitfiddling or even
lookuptable methods. Plus most other e.g. maintenance programmers will
quickly understand those, but will need comments for the Z_n method.

If you have an unsigned int or wider X with (possibly) more than one
bit set, you can easily and quickly isolate the lowest with X & -X.
And on nearly all (2sC) machines nowadays a signed one as well.

- David.Thompson1 at worldnet.att.net
Nov 20 '06 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Markus Ernst | last post by:
Hello Reading the follwing document: http://www.w3.org/TR/WD-positioning-970131#In-flow it seems very clear that position:relative should be relative to the parent element. So in the following...
8
by: Jaime Rios | last post by:
Hi, I created a COM AddIn for Word that performs the functions that it needs to, but I needed to add the ability for the toolbar created by the COM AddIn to remember it's last position and...
3
by: akunamatata | last post by:
Hello everyone, I contact this discussiongroup because I encountered a little problem with XSL. Let me explain it: I have following file "position.xml": <?xml version="1.0"?>...
4
by: Guy | last post by:
Hi, I read an XML file to an XMLDocument and iterate through its nodes. How do I get the XPath position (index) of a certain element? For example If I on the second "b" node I want to get "2": ...
6
by: Gérard Talbot | last post by:
Hello fellow stylers, When trying this page http://www.gtalbot.org/BrowserBugsSection/PercentualRelativePositioning.html I get different rendered layouts with IE 6, IE 7 beta 2, Firefox...
4
by: Petra Meier | last post by:
Hi, I use the common code to determine the position of an element getTop = function(o){ var nTop = null; if(o){ do{ nTop += o.offsetTop;
2
by: agbee1 | last post by:
Hello: I've finally made the effort to ween myself from overly using tables and use CSS for my positioning. However, I am having a problem with my navigational menu properly aligning in Firefox,...
0
by: crisscross27 | last post by:
Hi, I found a page called "myflashfetish" where you chan choose mp3 players for my space, well the problem is this, I wanted to place 2 or more players in myspace in a particular place, I read...
1
by: spynx | last post by:
import javax.swing.JOptionPane; import java.io.*; import java.util.Arrays; public class election5 { public static void main( String args ) {
8
by: muiz123 | last post by:
I study http://www.javascripttoolbox.com/lib/objectposition/index.php source and its doesn't work fine for the following code: (I hope both IE and firefox are working well) <!DOCTYPE HTML...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.