473,480 Members | 1,515 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

clean method to read bit position?

From a byte containing only 1 bit, I need to find the number representing
the bit position.

Example:
00010000 = 4
00000001 = 0

Is there a simpler method than looping?

Thanks,
Scott Kelley
Nov 14 '05 #1
19 20960
Scott Kelley <sc****@iccom.com> wrote:
From a byte containing only 1 bit, I need to find the number representing
the bit position. Example:
00010000 = 4
00000001 = 0 Is there a simpler method than looping?


Depends on what you call "simpler". You could use a lookup table, i.e.
an array with 256 elements (assuming your byte is 8 bits long) where
at index 1 0 is stored, at index 2 1, at index 4 2 etc. Now use your
byte as the index and you get the bit position. By putting a number
larger than 7 into all unused slots you even have a simple and fast
check if there's really only a single bit set in that byte...

Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@physik.fu-berlin.de
\__________________________ http://www.physik.fu-berlin.de/~toerring
Nov 14 '05 #2
In <r5********************@centurytel.net> "Scott Kelley" <sc****@iccom.com> writes:
From a byte containing only 1 bit, I need to find the number representing
the bit position.

Example:
00010000 = 4
00000001 = 0

Is there a simpler method than looping?


Dumb looping is by far the simplest method. And for 8-bit numbers,
probably also the fastest. For larger numbers, you may want to consider
a binary search.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #3
<Je***********@physik.fu-berlin.de> wrote in message
news:bu************@uni-berlin.de...
Scott Kelley <sc****@iccom.com> wrote:
From a byte containing only 1 bit, I need to find the number representing
the bit position.

Example:
00010000 = 4
00000001 = 0

Is there a simpler method than looping?


Depends on what you call "simpler". You could use a lookup table, i.e.
an array with 256 elements (assuming your byte is 8 bits long) where
at index 1 0 is stored, at index 2 1, at index 4 2 etc. Now use your
byte as the index and you get the bit position. By putting a number
larger than 7 into all unused slots you even have a simple and fast
check if there's really only a single bit set in that byte...


That is clearly a very fast technique, but remember that
a some implementations have a CHAR_BIT thing that indicates
more than 8 bits in a "char". A "char" is traditionally used
to represent an 8-bit byte, but it may be different on a
Deathstation implementation. You will likely want to qualify
with "unsigned char" to be sure that the value is not
sign-extended when promoted to an int for indexing the array.

Thus, you may have to use masking and shifting to force
an 8-bit value for the 256-element array index.

If you want to isolate the rightmost 1 bit, you could
use something like (ASSUMING TWOS-COMPLEMENT representation):

signed int foo = 12;
signed int right_bit_of_foo = (foo & -foo); /* this is 4 */

When using a twos-complement implementation (i.e., not
a Deathstation implementation), bit-wise AND of an integer
with its twos-complement isolates the rightmost 1 bit.

From there, you can use shifting and masking to find the
rightmost nonzero 8-bit value for indexing into the array.

2 cents worth. Your mileage may vary.
--
----------------------------
Jeffrey D. Smith
Farsight Systems Corporation
24 BURLINGTON DRIVE
LONGMONT, CO 80501-6906
http://www.farsight-systems.com
z/Debug debugs your Systems/C programs running on IBM z/OS!
Are ISV upgrade fees too high? Check our custom product development!
Nov 14 '05 #4
Scott Kelley wrote:
Example:
00010000 = 4
00000001 = 0
Is there a simpler method than looping?


Not for what you want, looping is the best answer. Think of what you
have to do above to get 4 with a single formula:

log(00010000[binary]) / log(2[decimal]) - 1 = 4

That's very expensive operations! It much easier to compare the suspect
value to powers of two one by one.

--
gabriel
Nov 14 '05 #5
Scott Kelley wrote:

From a byte containing only 1 bit, I need to find the number representing
the bit position.

Example:
00010000 = 4
00000001 = 0

Is there a simpler method than looping?


Bit 0 is set in 1
Bit 1 is set in 2
Bit 2 is set in 4
Bit 3 is set in 8
Bit 4 is set in 16
Bit 5 is set in 32
Bit 6 is set in 64
Bit 7 is set in 128

/* BEGIN bit_pos.c */

#include <stdio.h>

int bit_pos(unsigned char byte)
{
int pos;
unsigned char mask;

if (byte == 1) return 0;
if (byte == 2) return 1;
if (byte == 4) return 2;
if (byte == 8) return 3;
if (byte == 16) return 4;
if (byte == 32) return 5;
if (byte == 64) return 6;
if (byte == 128) return 7;
pos = 7;
mask = 128;
do {
++pos;
mask <<= 1;
} while (mask != byte);
return pos;
}

int main(void)
{
unsigned char byte;

byte = 0;
do {
if (byte != 0 && (byte & byte - 1) == 0) {
printf("Bit %d is set in %d\n", bit_pos(byte), byte);
}
} while (++byte != 0);
return 0;
}

/* END bit_pos.c */
--
pete
Nov 14 '05 #6

"Scott Kelley" <sc****@iccom.com> wrote in message
news:r5********************@centurytel.net...
From a byte containing only 1 bit, I need to find the number representing
the bit position.

Example:
00010000 = 4
00000001 = 0

Is there a simpler method than looping?

Thanks,
Scott Kelley


My preferred but CPU intensive solution is (int)( log(byte)/log (2) ) ;

Esojay
Nov 14 '05 #7
Da*****@cern.ch (Dan Pop) writes:
In <r5********************@centurytel.net> "Scott Kelley" <sc****@iccom.com> writes:
From a byte containing only 1 bit, I need to find the number representing
the bit position.

Example:
00010000 = 4
00000001 = 0

Is there a simpler method than looping?


Dumb looping is by far the simplest method. And for 8-bit numbers,
probably also the fastest. For larger numbers, you may want to consider
a binary search.


I imagine that a 256-entry lookup table is faster than dumb
looping for 8-bit numbers.
--
int main(void){char p[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv wxyz.\
\n",*q="kl BIcNBFr.NKEzjwCIxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+=strchr(p,*q++)-p;if(i>=(int)sizeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
Nov 14 '05 #8
In <87************@pfaff.stanford.edu> Ben Pfaff <bl*@cs.stanford.edu> writes:
Da*****@cern.ch (Dan Pop) writes:
In <r5********************@centurytel.net> "Scott Kelley" <sc****@iccom.com> writes:
From a byte containing only 1 bit, I need to find the number representing
the bit position.

Example:
00010000 = 4
00000001 = 0

Is there a simpler method than looping?


Dumb looping is by far the simplest method. And for 8-bit numbers,
probably also the fastest. For larger numbers, you may want to consider
a binary search.


I imagine that a 256-entry lookup table is faster than dumb
looping for 8-bit numbers.


Hard to say. If the table is not in the cache when you need it...
And to bring it in cache, the CPU may have to flush some other useful
data...

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #9

"pete" <pf*****@mindspring.com> wrote in message
news:40***********@mindspring.com...
Scott Kelley wrote:

From a byte containing only 1 bit, I need to find the number representing the bit position.

Example:
00010000 = 4
00000001 = 0

Is there a simpler method than looping?
Bit 0 is set in 1
Bit 1 is set in 2
Bit 2 is set in 4
Bit 3 is set in 8
Bit 4 is set in 16
Bit 5 is set in 32
Bit 6 is set in 64
Bit 7 is set in 128

/* BEGIN bit_pos.c */

#include <stdio.h>

int bit_pos(unsigned char byte)
{
int pos;
unsigned char mask;

if (byte == 1) return 0;
if (byte == 2) return 1;
if (byte == 4) return 2;
if (byte == 8) return 3;
if (byte == 16) return 4;
if (byte == 32) return 5;
if (byte == 64) return 6;
if (byte == 128) return 7;
pos = 7;
mask = 128;
do {
++pos;
mask <<= 1;
} while (mask != byte);
return pos;
}

int main(void)
{
unsigned char byte;

byte = 0;
do

if (byte != 0 && (byte & byte - 1) == 0) {
printf("Bit %d is set in %d\n", bit_pos(byte), byte);
}
} while (++byte != 0);
return 0;
}

/* END bit_pos.c */
--
pete


I prefer a switch statement to 'if's (cos it's easier to type):

switch(byte){
case 1: return 0;
case 2: return 1;
case 4: return 2;
...
default: return -1;
}

Sean
Nov 14 '05 #10
On Tue, 20 Jan 2004 15:19:41 -0000, "ESOJAY" <es******@hotmail.com>
wrote:

"Scott Kelley" <sc****@iccom.com> wrote in message
news:r5********************@centurytel.net...
From a byte containing only 1 bit, I need to find the number representing
the bit position.

Example:
00010000 = 4
00000001 = 0

Is there a simpler method than looping?

Thanks,
Scott Kelley


My preferred but CPU intensive solution is (int)( log(byte)/log (2) ) ;


Then I should definitely avoid software written by you ;-)

On my system (gcc 3.3.1 cygwin)

(int) (log(8)/log(2))

yields 2.
--
Horst

Nov 14 '05 #11
I prefer a switch statement to 'if's (cos it's easier to type):

switch(byte){
case 1: return 0;
case 2: return 1;
case 4: return 2;
...
default: return -1;
}

Sean

Were you being literal with the above statement? Cannot find any reference
to a switch statement being used to return a value. All info I find
discusses only the form I'm used to:

case 1: {x = 0; break;}
case 2: {x = 1; break;}

If it can be used as you show, that would be very useful to me.

Scott Kelley
Nov 14 '05 #12
Sean Kenwrick wrote:
I prefer a switch statement to 'if's (cos it's easier to type):

switch(byte){
case 1: return 0;
case 2: return 1;
case 4: return 2;
...
default: return -1;
}


/* BEGIN bit_pos.c */

#include <stdio.h>

int bit_pos(unsigned char byte)
{
int pos = 7;
unsigned char mask = 1u << 7;

do {
++pos;
mask <<= 1;
} while (mask != byte);
return pos;
}

#define bit_pos(A) \
((A) == 1u << 0 ? 0 \
: (A) == 1u << 1 ? 1 \
: (A) == 1u << 2 ? 2 \
: (A) == 1u << 3 ? 3 \
: (A) == 1u << 4 ? 4 \
: (A) == 1u << 5 ? 5 \
: (A) == 1u << 6 ? 6 \
: (A) == 1u << 7 ? 7 \
: (bit_pos)(A))

int main(void)
{
unsigned char byte;

byte = 1;
do {
printf("Bit %d is set in %d\n", bit_pos(byte), byte);
byte <<= 1;
} while (byte != 0);
return 0;
}

/* END bit_pos.c */
--
pete
Nov 14 '05 #13
"Scott Kelley" <sc****@iccom.com> writes:
I prefer a switch statement to 'if's (cos it's easier to type):

switch(byte){
case 1: return 0;
case 2: return 1;
case 4: return 2;
...
default: return -1;
}

Sean

Were you being literal with the above statement? Cannot find any reference
to a switch statement being used to return a value. All info I find
discusses only the form I'm used to:

case 1: {x = 0; break;}
case 2: {x = 1; break;}

If it can be used as you show, that would be very useful to me.


A return statement can be used within a switch statement just as
it can be used in any other context. I hope you don't think that
it causes the switch statement itself to have a value; rather, it
returns a value from the function just as in any other context.
--
int main(void){char p[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv wxyz.\
\n",*q="kl BIcNBFr.NKEzjwCIxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+=strchr(p,*q++)-p;if(i>=(int)sizeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
Nov 14 '05 #14

"Ben Pfaff" <bl*@cs.stanford.edu> wrote in message
news:87************@pfaff.stanford.edu...
"Scott Kelley" <sc****@iccom.com> writes:
I prefer a switch statement to 'if's (cos it's easier to type):

switch(byte){
case 1: return 0;
case 2: return 1;
case 4: return 2;
...
default: return -1;
}

Sean

Were you being literal with the above statement? Cannot find any reference to a switch statement being used to return a value. All info I find
discusses only the form I'm used to:

case 1: {x = 0; break;}
case 2: {x = 1; break;}

If it can be used as you show, that would be very useful to me.


A return statement can be used within a switch statement just as
it can be used in any other context. I hope you don't think that
it causes the switch statement itself to have a value; rather, it
returns a value from the function just as in any other context.


Do you mean that it would be used as follows?

char myfunction(char);
.. . .

bit = myfunction(x);

char myfunction(byte) {
switch(byte){
case 1: return 0;
case 2: return 1;
case 4: return 2;
...
default: return -1;
}
}

Nov 14 '05 #15
"Scott Kelley" <sc****@iccom.com> writes:
A return statement can be used within a switch statement just as
it can be used in any other context. I hope you don't think that
it causes the switch statement itself to have a value; rather, it
returns a value from the function just as in any other context.


Do you mean that it would be used as follows?

char myfunction(char);
. . .

bit = myfunction(x);

char myfunction(byte) {
switch(byte){
case 1: return 0;
case 2: return 1;
case 4: return 2;
...
default: return -1;
}
}


Yes (although I probably would not use `char' as the return
type).
--
"C has its problems, but a language designed from scratch would have some too,
and we know C's problems."
--Bjarne Stroustrup
Nov 14 '05 #16
Scott Kelley <sc****@iccom.com> wrote:
"Ben Pfaff" <bl*@cs.stanford.edu> wrote in message
news:87************@pfaff.stanford.edu...
"Scott Kelley" <sc****@iccom.com> writes: Do you mean that it would be used as follows?

char myfunction(char);
. . . bit = myfunction(x); char myfunction(byte) {
switch(byte){
case 1: return 0;
case 2: return 1;
case 4: return 2;
...
default: return -1;
}
}


Yes, definitely. There's nothing wrong with that. It's not different
from e.g. returning from within a for loop. You can even call exit()
from within a switch;-)
Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@physik.fu-berlin.de
\__________________________ http://www.physik.fu-berlin.de/~toerring
Nov 14 '05 #17
"Scott Kelley" <sc****@iccom.com> wrote in message news:<r5********************@centurytel.net>...
From a byte containing only 1 bit, I need to find the number representing
the bit position.

Example:
00010000 = 4
00000001 = 0

Is there a simpler method than looping?


Define simpler? ;) The following is O(1) for 8-bits...

#include <stdio.h>

int main(void)
{
static int table[8] = { 7, 0, 5, 1, 6, 4, 3, 2 };
unsigned x;

for (x = 1; x < 256; x <<= 1) /* x: 2**[0..7] */
{
printf("0x%02X: ", x);
printf("bit %d\n", table[((x * 0x3A) >> 5) & 7]);
}

return 0;
}

Of course, the (hashing) method is not likely to be practical for such
narrow integers. BTW, it's based on...

http://groups.google.com/groups?thre...is.demon.co.uk

--
Peter
Nov 14 '05 #18
[Someone wrote]
switch(byte){
case 1: return 0;
...

In article <news:9s********************@centurytel.net>
Scott Kelley <sc****@iccom.com> writes:Were you being literal with the above statement? Cannot find any reference
to a switch statement being used to return a value. All info I find
discusses only the form I'm used to:

case 1: {x = 0; break;}
case 2: {x = 1; break;}


I suspect you think that switch/case constructs are quite restricted
(which is often true in other languages). C is a bit lower level
than that -- a switch is just a goto in disguise:

volatile unsigned char *dev;
unsigned char *mem;
...
i = n / 8;
switch (n % 8) {
do {
*dev = *mem++;
case 7: *dev = *mem++;
case 6: *dev = *mem++;
case 5: *dev = *mem++;
case 4: *dev = *mem++;
case 3: *dev = *mem++;
case 2: *dev = *mem++;
case 1: *dev = *mem++;
case 0: ;
} while (i-- != 0);
}

This construct, called "Duff's Device" after Tom Duff (see the
FAQ), is entirely valid Standard C. The "switch" is just a goto,
and each "case" label is just a target label. (The FAQ's version
is slightly different -- I looked it up after typing in the above.)

The only "magic" about switch/case is that a case "looks upwards"
in enclosing brace scope blocks to find the innermost enclosing
"switch" statement, and places the appropriate "if (switch_expr ==
this_case_constant) goto here" up there. (Old non-optimizing
C compilers actually implemented this by compiling:

switch (expr) {
...
}

as if it were:

tmp = expr;
goto just_past_end_of_switch;
...
goto around;
just_past_end_of_switch:
if (tmp == first_value) goto first_label;
if (tmp == second_value) goto second_label;
...
if (tmp == last_value) goto last_label;
if (there was a default) goto default_label;
around:

This allows the compiler to "forget" the code in between, and
remember only the <value,label> pairings. The <value,label>
pairs can also be compared more efficiently than with a straight
sequence of "if"s; e.g., if the table is dense this turns into:

if (tmp >= first_value && tmp <= last_value)
goto label[tmp - first_value];
if (there was a default)
goto default_label;
around:

and in other cases the compiler could generate an inline
binary search.)

The fact that "case" labels are really just goto-labels is
also the (or at least "a") logical reason behind the requirement
for a "break" statement if you did not want to fall through
from one case to the next. Just as:

if (x == 1) goto label;
f();
label:
g();

executes g() even when x == 2, so does a switch/case.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #19
Ben Pfaff <bl*@cs.stanford.edu> wrote in message news:<87************@pfaff.stanford.edu>...
"Scott Kelley" <sc****@iccom.com> writes:

char myfunction(byte) {
switch(byte){
case 1: return 0;
case 2: return 1;
case 4: return 2;
...
default: return -1;
}
}


Yes (although I probably would not use `char' as the return
type).


Ben's referring to situations where plain char is unsigned and constructs like...

if (myfunction(blah) == -1)

....may not work as expected, i.e. UCHAR_MAX is not -1.

--
Peter
Nov 14 '05 #20

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

Similar topics

2
2114
by: cricfan | last post by:
I'm parsing a text file to extract word definitions. For example the input text file contains the following content: di.va.gate \'di_--v*-.ga_-t\ vb pas.sim \'pas-*m\ adv : here and there :...
18
5650
by: JG | last post by:
Does anyone know a standard (or supported on Linux, Mac, Win32) way to clear a read stream buffer (standard ANSI C file stream)? I would even settle for a platform specific way of doing it. ...
7
22376
by: Eric | last post by:
I am trying to save the "last read" position of a file using a StreamReader object. I am reading the lines of the file using StreamReader.ReadLine and then saving the current position in the...
3
10313
by: gencode | last post by:
I need to make a javascript read a web directory from a remote site (ie "http://remotesite.com/images") (The remote die does not have an index.htm and does have directory listing enabled) I...
5
3278
by: lovecreatesbea... | last post by:
The condition at line 31 is added to check if the program finished to read the whole file. Is it needed and correct? Thank you. #include <fstream> #include <iostream> #include <string> using...
1
3406
by: tschroeder250 | last post by:
I want to create an abstract class that contains a static method. This method returns an instance of the derived class. In my case, I have a class called Record which is inherited by HeaderRecord...
0
3836
by: martinmercy2001 | last post by:
Could any body help me with creating a ring buffer class using a string. use memory circular buffer not an IO buffer. just read, write and seek method. Read method should take anumber and return the...
0
6085
by: LukasMalik | last post by:
Hi all, I have 2 different read methods: 1) public void Read() { while(true) { oSerialPort.Read(bytesToReadArray, 0, bytesToReadArray.Lenght);
3
1577
by: Raymond Chiu | last post by:
Dear all, Now I have the simple task to read text file line by line into database (SQL Server 2000). If the text file is divided into different fields according to the number of characters,...
0
7041
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
6908
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
7044
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7084
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...
1
6739
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
6929
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
4779
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4481
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
2984
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.