473,396 Members | 1,966 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,396 software developers and data experts.

Checking bits states

Hello,

I have an unsigned int variable, which is really a set of bits.
So what I need, is to check specific bit state: on/off (0 or 1).
For example, I need to know is the 16-th bit is on.
How can I do it?

Thanks

Feb 5 '06 #1
20 2040
TB
cozzzy sade:
Hello,

I have an unsigned int variable, which is really a set of bits.
So what I need, is to check specific bit state: on/off (0 or 1).
For example, I need to know is the 16-th bit is on.
How can I do it?

Thanks


Use the operators &, |, ^,~, << and >> when dealing with bit patterns.
Any decent c++ book should cover this.

--
TB @ SWEDEN
Feb 5 '06 #2
Thanks for your answer.
But the fact is I do know that operators &, |, ^,~, << and >> are what
I need.
But I'm not very familiar with bit logics.
So maybe someone can give me a simple hint?

Feb 5 '06 #3
cozzzy wrote:
Hello,

I have an unsigned int variable, which is really a set of bits.
So what I need, is to check specific bit state: on/off (0 or 1).
For example, I need to know is the 16-th bit is on.
How can I do it?


You might consider using std::bitset<> instead.
Best

Kai-Uwe Bux
Feb 5 '06 #4
cozzzy wrote:
Thanks for your answer.
But the fact is I do know that operators &, |, ^,~, << and >> are what
I need.
But I'm not very familiar with bit logics.
So maybe someone can give me a simple hint?


unsigned int x;

/*...manipulate 'x'....*/

/* fixed pitch font req'd to view the following... */
/* 1111 11
* bit nbrs: 5432 1098 7654 3210
* ---- ---- ---- ----
* binary: 1000 0000 0000 0000 = hex 0x8000
* ----
* bit vals when set: 8421
*/
/* if bit number 15 (the 16th bit) is set in 'x' */
if ( x & 0x8000 )
/* do stuff... */

Larry
Feb 5 '06 #5
Thanks a lot!

Feb 5 '06 #6
On Sun, 05 Feb 2006 15:08:23 -0500, Kai-Uwe Bux <jk********@gmx.net>
wrote:

You might consider using std::bitset<> instead.


Why? What are the advantages for someone who has "an unsigned int
variable, which is really a set of bits"? Im really interested.

Best,
Roland Pibinger
Feb 5 '06 #7
Roland Pibinger wrote:
On Sun, 05 Feb 2006 15:08:23 -0500, Kai-Uwe Bux <jk********@gmx.net>
wrote:

You might consider using std::bitset<> instead.


Why? What are the advantages for someone who has "an unsigned int
variable, which is really a set of bits"? Im really interested.


To someone who does not know the typical bit fiddling idioms that go with
using an unsigned int as a set representation, std::bitset<> clearly has
the advantage of a much nicer interface. Keep in mind that my advise was
addressing someone who did not know how to treat an unsigned int as a set
of bits.

However, for someone who does know the bit fiddling idioms, std::bitset<>
still reduces the likelihood of glitches. After all, these expressions with
bit shifting and xor-ing and stuff are all a little bit error prone.
Best

Kai-Uwe Bux
Feb 5 '06 #8
> After all, these expressions with bit shifting and xor-ing
and stuff are all a little bit error prone.


Come on, testing if 16th bit is set is not Rocket Science - it's
fundamentals of the language, and for crying out loud, computer
science. Knuth would roll in his grave is he were dead.

Feb 6 '06 #9

Kai-Uwe Bux wrote:
Roland Pibinger wrote:
On Sun, 05 Feb 2006 15:08:23 -0500, Kai-Uwe Bux <jk********@gmx.net>
wrote:

You might consider using std::bitset<> instead.


Why? What are the advantages for someone who has "an unsigned int
variable, which is really a set of bits"? Im really interested.


To someone who does not know the typical bit fiddling idioms that go with
using an unsigned int as a set representation, std::bitset<> clearly has
the advantage of a much nicer interface.


I disagree. Things that normally work when dealing with bitmasks don't
with bitset. For instance: if (bits & VALUE) has to be instead if
((bits & VALUE).any()) as I recall when using it.

std::bitset<> is useful for values larger than the bitsize of whatever
the largest type is in your system. When implementing bitboards for
chinese chess I used it (board is 90 squares) but I can't imagine it
being particularly useful for anything else.

Feb 6 '06 #10
ro**********@gmail.com wrote:

Kai-Uwe Bux wrote:
Roland Pibinger wrote:
> On Sun, 05 Feb 2006 15:08:23 -0500, Kai-Uwe Bux <jk********@gmx.net>
> wrote:
>>
>>You might consider using std::bitset<> instead.
>
> Why? What are the advantages for someone who has "an unsigned int
> variable, which is really a set of bits"? Im really interested.
To someone who does not know the typical bit fiddling idioms that go with
using an unsigned int as a set representation, std::bitset<> clearly has
the advantage of a much nicer interface.


I disagree. Things that normally work when dealing with bitmasks don't
with bitset. For instance: if (bits & VALUE) has to be instead if
((bits & VALUE).any()) as I recall when using it.


Maybe that "things that normally work when dealing with bitmasks don't with
bitset"; however, this kind of frustrated expectations hardly applies to
someone "who does not know the typical bit fiddling idioms".

std::bitset<> is useful for values larger than the bitsize of whatever
the largest type is in your system.
That too.

When implementing bitboards for
chinese chess I used it (board is 90 squares) but I can't imagine it
being particularly useful for anything else.


Well, if you see an advantage for std::bitset in some cases, then why would
you want to maintain a second set of language idioms for the same task just
in those cases where your number of flags happens to be less than
<implementation defined constant>?

Also, I find that the std::bitset idioms convey intend more clearly. I would
prefer

if ( flag[3] ) {...} or flag[3] = true;

to

if ( flag & 8 ) {...} or flag |= 8;

any day. However, I agree that things like these are very much a matter of
opinion.
Best

Kai-Uwe Bux
Feb 7 '06 #11
On 6 Feb 2006 14:01:08 -0800, ro**********@gmail.com wrote:
std::bitset<> is useful for values larger than the bitsize of whatever
the largest type is in your system. When implementing bitboards for
chinese chess I used it (board is 90 squares) but I can't imagine it
being particularly useful for anything else.
Well, chalk-up yet another subject you know nothing about. That
doesn't stop you from commenting with a boatload of assumptions
though does it.

The people who do embedded programming are laughing *at* you, pal;
not with you. Additionally, there are thousands if not tens of
thousands of programs "out there" that monitor, control and test
hardware. All kinds of hardware.
but I can't imagine it
being particularly useful for anything else.


(8-O)
You have never heard of using C++ to interface - read and write - to
hardware registers? I said hardware registers... ooo, boy. You can
use std::bitsets to do that.

Once again, I did my first video disc recorder/player in the early
nineties. That's what software engineers do; learn to program real
world problem domains. Not just learn one myopic academic subject
and then discount anything and everything they've never heard of.

Examples:
http://cplus.about.com/od/advancedtu.../aa042203b.htm

http://www.phptr.com/articles/articl...&seqNum=4&rl=1

And I didn't even mention device drivers... oh, I just did.

Some drink at the fountain of knowledge... others just gargle.
Feb 7 '06 #12

JustBoo wrote:
Once again, I did my first video disc recorder/player in the early
nineties.


Good for you Mr. "Boo".

Thanks for the links.

Feb 7 '06 #13

Kai-Uwe Bux wrote:
Also, I find that the std::bitset idioms convey intend more clearly. I would
prefer

if ( flag[3] ) {...} or flag[3] = true;

to

if ( flag & 8 ) {...} or flag |= 8;
What about if (flag & 7)?

Also I recall another thing that bugged me: the above would have to be
flag & std::bitset<X>(7). This does make some amount of sense given
what you are actually meaning to do but the added complexity often
isn't necessary. I use bitset when I need what it offers, otherwise I
use a type that fits the mask I am working with.

any day. However, I agree that things like these are very much a matter of
opinion.


Certainly. I've certainly seen worst attempts at creating a generic
bitmask type.

Feb 7 '06 #14
If using std::bitset, it sounds awfully like bad engineering practise -
using "magic" numbers, certainly it would be better practise to use
symbolic names for hardware registers and design the API around that.
At that stage using bit-fields, bitset, boolean arithmetic, whatnot,
doesn't make any difference. It's just implementation detail.

However, recommending std::bitset because it is *simpler*, is
suspectible: is it really simpler not to learn the language you using
than use some specific class written on top of the language
*fundamentals* like AND, OR, XOR. It seems these days be simpler not to
know what the hell you are doing and just use shrink-wrapped class. I
disagree with that: I want to know what I am doing, call me weird.

Feb 7 '06 #15
persenaama wrote:

[snip}
However, recommending std::bitset because it is *simpler*, is
suspectible: is it really simpler not to learn the language you using
than use some specific class written on top of the language
*fundamentals* like AND, OR, XOR. It seems these days be simpler not to
know what the hell you are doing and just use shrink-wrapped class. I
disagree with that: I want to know what I am doing, call me weird.


Hm, would you apply the same kind of reasoning to basic data structures
like doubly linked lists or search trees? These are also clearly
fundamentals of compupter science and everybody should known how to
implement them. Do you then suspect anybody who recommends the use of
std::list<> or std::map<> of promoting laziness and ignorance?
Best

Kai-Uwe Bux

Feb 7 '06 #16
>Hm, would you apply the same kind of reasoning to basic data structures
like doubly linked lists or search trees? These are also clearly
fundamentals of compupter science and everybody should known how to
implement them.
What kind of reasoning would that be? Everybody doesn't have to
implement bitwise operations.

Do you then suspect anybody who recommends the use of
std::list<> or std::map<> of promoting laziness and ignorance?


Thank you for not quoting what you are replying to, without that what
you are asking almost makes sense. It would make sense if I was
proposing something like that, but I am not. Here's what I wrote,
quote:

"recommending std::bitset because it is *simpler*, is suspectible"

If you think, that I think that writing own std::list implementation is
simpler, then your question would make any sense to begin with. Your
question is based on incorrect assumption, I won't humor you by
defending a point of view that exists only in your own imagination.

I don't have a problem using std::bitset. I do have a problem keeping a
straight face if someone uses std::bitset for the reason that do not
understand bitwise and.

Feb 8 '06 #17
persenaama wrote:
Hm, would you apply the same kind of reasoning to basic data structures
like doubly linked lists or search trees? These are also clearly
fundamentals of compupter science and everybody should known how to
implement them.
What kind of reasoning would that be? Everybody doesn't have to
implement bitwise operations.

Do you then suspect anybody who recommends the use of
std::list<> or std::map<> of promoting laziness and ignorance?


Thank you for not quoting what you are replying to, without that what
you are asking almost makes sense.


I did quote a complete paragraph. And it was exactly that paragraph that I
responded to. I have no idea, what you are talking about.
It would make sense if I was
proposing something like that, but I am not. Here's what I wrote,
quote:

"recommending std::bitset because it is *simpler*, is suspectible"

You also wrote, and I quoted:

"It seems these days be simpler not to know what the hell you are doing and
just use shrink-wrapped class. I disagree with that: I want to know what I
am doing, call me weird."

Now, how and why does that reasoning not apply to std::list<> and
std::map<> ?

If you think, that I think that writing own std::list implementation is
simpler, then your question would make any sense to begin with.
Nope, my question makes sense, if "to know what the hell you are doing" as
opposed to "using shrink-wrapped class" is an alternative on which, you
seem to say, we ought to come down on the side of knowing what we are
doing.

Your
question is based on incorrect assumption, I won't humor you by
defending a point of view that exists only in your own imagination.
Well, I am glad to learn that you did not meant what I read. I am pretty
sure though that I read it because you wrote it.

I don't have a problem using std::bitset. I do have a problem keeping a
straight face if someone uses std::bitset for the reason that do not
understand bitwise and.


Thanks for this clarification.
Best

Kai-Uwe Bux
Feb 8 '06 #18

Kai-Uwe Bux wrote:
You also wrote, and I quoted:

"It seems these days be simpler not to know what the hell you are doing and
just use shrink-wrapped class. I disagree with that: I want to know what I
am doing, call me weird."

Now, how and why does that reasoning not apply to std::list<> and
std::map<> ?


IMHO it does. You should implement a linked list and a binary tree at
least once so that you understand what they are doing. Once that is
done though there is no reason to continue doing so unless you have a
good reason why the standard containers aren't what you need. These
classes are mature, robust, and well optimized most of the time and
they have good interfaces that meet a wide variety of requirements
though obviously not everything.

By using primatives and bitwise operators you aren't reinventing the
wheel like you do by not using standard containers. Primatives and
bitwise operators and the bitset class provide very similar services
and interfaces. The bitwise operators just aren't capable of dealing
with masks past a certain size. Until you're dealing with masks of
that size (and honestly that isn't very often) the differences between
primatives and bitset are simply a matter of taste and style.

Feb 8 '06 #19
>Now, how and why does that reasoning not apply to std::list<> and
std::map<> ?


The reasoning aimed to establish that I rather know what I am doing
than code with hunch and feeling (at best). In that sense the reasoning
DOES apply to std::list and std::map, I feel confident that I know how
to use them efficiently and safely.

The discussion was about ways to check if a bit is set.

Checking if a bit is set, is a simple bitwise-and, which incidetally is
built-in into the language: library, standard or any other kind is not
required.

Using std::bitset is not frowned upon by yours truly, but using it as
replacement for knowledge of what bitwise-and is and advice leading to
the same outcome is something that I DO regard with highest suspicion.

Feb 8 '06 #20
bool isBitSet(unsigned int v, int n)
{
return v & (1 << n);
}

Feb 8 '06 #21

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

Similar topics

6
by: LRW | last post by:
What I need to do is a comparison to see if a variable equals none of the 48 contiguous United States, but as efficiently as possible. The best way I can come up with the the textbook method of :...
2
by: William Morris | last post by:
Apologies in advance for the cross-post. Not sure if this is better handled in ASP code or TransactSQL. Windows2000 Server SQL 2000 tblPeople contactid int firstname varchar(25) lastname...
67
by: Steven T. Hatton | last post by:
Some people have suggested the desire for code completion and refined edit-time error detection are an indication of incompetence on the part of the programmer who wants such features. ...
99
by: Mikhail Teterin | last post by:
Hello! Consider the following simple accessor function: typedef struct { int i; char name; } MY_TYPE; const char *
4
by: Dave Rahardja | last post by:
I have the following program that uses an array of chars to simulate a bit set: --------- // An out-of-bounds exception class BoundsException {}; template <int bits = 1> class Bitset
4
by: felixnielsen | last post by:
imagine a hollow cube. every wall can have one of two states: open or closed. This would take 6 bits to represent. Now, i allso neew to know whitch way i entered the room, this could be...
16
by: chandanlinster | last post by:
As far as I know floating point variables, that are declared as float follow IEEE format representation (which is 32-bit in size). But chapter1-page no 9 of the book "The C programming language"...
77
by: borophyll | last post by:
As I read it, C99 states that a byte is an: "addressable unit of data storage large enough to hold any member of the basic character set of the execution environment" (3.6) and that a byte...
59
by: riva | last post by:
I am developing a compression program. Is there any way to write a data to file in the form of bits, like write bit 0 then bit 1 and then bit 1 and so on ....
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
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
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
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
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...

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.