473,836 Members | 1,582 Online
Bytes | Software Development & Data Engineering Community
+ 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
19 21004
On Tue, 20 Jan 2004 15:19:41 -0000, "ESOJAY" <es******@hotma il.com>
wrote:

"Scott Kelley" <sc****@iccom.c om> wrote in message
news:r5******** ************@ce nturytel.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(unsigne d 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.c om> 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[]="ABCDEFGHIJKLM NOPQRSTUVWXYZab cdefghijklmnopq rstuvwxyz.\
\n",*q="kl BIcNBFr.NKEzjwC IxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+= strchr(p,*q++)-p;if(i>=(int)si zeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
Nov 14 '05 #14

"Ben Pfaff" <bl*@cs.stanfor d.edu> wrote in message
news:87******** ****@pfaff.stan ford.edu...
"Scott Kelley" <sc****@iccom.c om> 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.c om> 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.c om> wrote:
"Ben Pfaff" <bl*@cs.stanfor d.edu> wrote in message
news:87******** ****@pfaff.stan ford.edu...
"Scott Kelley" <sc****@iccom.c om> 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***********@p hysik.fu-berlin.de
\______________ ____________ http://www.physik.fu-berlin.de/~toerring
Nov 14 '05 #17
"Scott Kelley" <sc****@iccom.c om> wrote in message news:<r5******* *************@c enturytel.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******* *************@c enturytel.net>
Scott Kelley <sc****@iccom.c om> 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_const ant) 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_o f_switch;
...
goto around;
just_past_end_o f_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.stanfor d.edu> wrote in message news:<87******* *****@pfaff.sta nford.edu>...
"Scott Kelley" <sc****@iccom.c om> 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(bla h) == -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
2141
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 : THROUGHOUT I am trying to obtain words between two literal backslashes (\ .. \). I am not able to match words between two literal backslashes using the regxp - re.compile(r'\\*\\').
18
5709
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. And no, I know I can use direct low level I/O or non-buffered to do reads, but for my app, I need the buffering. I can implement myself, but this is not optimal. Example, I open a read only file using fopen(). I periodically know
7
22410
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 file. My problem is that on subsequent reads, the starting position is not correct. I have tried many different ways to increment the file position value, but I cannot get it to work so that on the next read, the read starts at the correct...
3
10327
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 have seen many samples but they all use frames or iframes, all I want is a method that you can say <body onload="readremotedir('http://remotesite.com/images');"> and the method would get the directory listings and populate an array
5
3308
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 namespace std; int read(string filename, int last_pos) {
1
3492
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 and DataRecord. Record defines the method Read(file) which reads data in from a file, creates an instance of itself, and returns the populated instance to the caller. IOW, I want HeaderRecord and DataRecord to share this Read() method, and I...
0
3873
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 string. write method should take a string. seek should take a number and return nuthing. use three member variables a buffer itself as a string, read_position, write_position. use >>, << methods. I have tried this code but i need full...
0
6148
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
1591
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, What is the best method to read into database. In Oracle, I know it has sql loader. As to SQL Server, What should be? Do I need to write the program to read each characters and line by line? Thanks,
0
9818
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10843
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10546
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10589
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9371
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5648
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5825
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4448
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3112
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.