Program to toggle nth bit in C

S

sksoule

Hi,

Can anyone please tell me how to toggle a nth bit. For example, I am
having a variable which is of 8 bits. I want to toggle the nth bit.

Regards,
Santosh
 
N

nsimeonov

Oh boy... I'm tempted to suggest you a carreer change or plainly tell
you how big of an id**t you are. Really! Want to know why? One word:
research! Did you ever tried searching with google about bitwise
operations in C? I spent 1 minute just to prove I was right and I found
a couple of sites explaining it very well. This one for example:
http://www.cprogramming.com/tutorial/bitwise_operators.html

Please try to start thinking of your own instead of asking stupid
questions on the newsgroups. I could give you a much better answer, but
WHY? Noone else but you will ever read it because there are so many
resources out there so why bother. If you give me a reasonable answer I
will post you the exact code to do SET, CLEAR or TOGGLE the Nth bit.

Hope my answer helps you in any way,
Nikolay



(e-mail address removed) напиÑа:
 
R

Richard Heathfield

(e-mail address removed) said:
Oh boy... I'm tempted to suggest you a carreer change or plainly tell
you how big of an id**t you are.

It seemed like a reasonable question to me, albeit one that is answered in
the FAQ and in K&R, which it would have been wise of the OP to check first.
Really! Want to know why? One word: research!

Okay, let's see where your "research" takes us...
Did you ever tried searching with google about bitwise operations in C?

Google is not selective. You could write a page like this:

+----------------------------------------------------------+
| http://www.lousytips.disinformation.org/bitunwise.html |
+----------------------------------------------------------+
| |
| Bitwise operations in C |
| ----------------------- |
| |
| C doesn't support bitwise operations. Use BASIC instead. |
| |
+----------------------------------------------------------+

....and Google would cheerfully index it without prejudice.

I spent 1 minute just to prove I was right and I found
a couple of sites explaining it very well. This one for example:
http://www.cprogramming.com/tutorial/bitwise_operators.html

That site has a very poor reputation with regard to C programming. But never
mind that - let's look at the page itself:

"Generally, as a programmer you don't need to concern yourself about
operations at the bit level." Well, that's as maybe, but if he didn't need
to know the answer he wouldn't have asked the question. Personally, I find
myself doing bit manipulations fairly regularly. Not only do they have
useful applications in cryptography and graphics, but they are also
essential for n-bit numbers (the more so when n > sizeof(largest integer
type) * CHAR_BIT), and useful for such things as Bloom filters.

After three and a half lines of generalised text, we find (or at least, I
found) advertisements for Prismtech, Microsoft, and "National", whatever
that is. A naive reader might well stop right there, thinking the article
was over. Interspersing ads in the text is thoughtless and exploitative.

"By convention, in C and C++ you can think about binary numbers..."

There is no such thing as a binary number. The author is confusing number
with number representation.

"10000000 is 128"

No, it isn't.

"the results of the left and right shift operators are not implementation
dependent for unsigned numbers"

Yes, they are, whether the author means "unsigned numbers" or "unsigned
types". The result of 1L << 32 is undefined on some systems, and
well-defined on others.

"Note that in this example, we're using integers, which are either 2 or 4
bytes..."

It is not clear whether the author means that integers are guaranteed to be
2 or 4 bytes (which they are not). If that is not what is meant, though, it
is hard to see why the author would have bothered to say anything, since
the example in question is simply: return number << power; which is not
dependent on any particular integer size, except in terms of the allowable
values of power, which the example does not check at all.

"128 * 2 = 256, and we can't even store a number that big in a byte..."

We can if CHAR_BIT >= 9.

The page has other such errors, and I cannot recommend it.

So much for "research". There is more to research than typing a few search
terms into Google.
 
N

nsimeonov

Ok. Do you like this one better?
http://www.codeproject.com/cpp/bitbashing.asp

Why do we keep arguing? Bitwise operators are something VERY BASIC and
it's irrelevant to explain them on the newsgroups when you may find a
few nice articles for less than 5 minutes. Come on, BITWISE operators:
AND, OR, XOR, NOT - is there someone out there who is trying to program
and never heard of them. Multiplication on powers of 2 isn't so hard to
figure out if you ever heard of binary and hexadecimal numbers. If you
don't - well you either should consider a carreer change or read a book
about the basics.

If you have so much time why didn't you answer the question and even
better - write an article and publish it on codeproject or your blog or
somewhere else so other newbies can find it?
 
A

Andre Reffhaug


Who likes what better? Quoting context is a Good Thing.
Why do we keep arguing? Bitwise operators are something VERY BASIC and
it's irrelevant to explain them on the newsgroups when you may find a
few nice articles for less than 5 minutes. Come on, BITWISE operators:
AND, OR, XOR, NOT - is there someone out there who is trying to program
and never heard of them. Multiplication on powers of 2 isn't so hard to
figure out if you ever heard of binary and hexadecimal numbers. If you
don't - well you either should consider a carreer change or read a book
about the basics.
If you have so much time why didn't you answer the question and even
better - write an article and publish it on codeproject or your blog or
somewhere else so other newbies can find it?

I usually only lurk in this group, but your manner of answering the OP
in this thread actually got me quite worked up. You accuse Richard
Heathfield of not spending his time right correcting you over answering
the OP, while you yourself have done little to nothing to help out.
Advising people to change careers and plainly calling them idiots is
nothing but bad form and childish plays, and can't be designed to do
anything other than boost your own ego.

If you think a post is unwarranted, behave like a civilized human being
when responding. There is nothing wrong in telling the OP to do more
research, or perhaps pointing him/her in certain directions, but plain
out attacking them like you are doing here hasn't got a place anywhere.
You also have the opportunity to skip past their post entirely,
regarding it as a waste of time for you in your wisdom to answer such
trivial questions. What is and what is not relevant on a newsgroup is
not for you to decide, luckily. The OPs question is more than relevant
for comp.lang.c, even if he could have invested more time researching
and reading.
 
N

nsimeonov

Richard said:

Besides about the original question the first site had a couple of code
snippets that one can use :

int mult_by_pow_2(int number, int power)
{
return number<<power;
}


int a = b ^ mult_by_pow_2(1, n);

for example... or the correct answer of

int result = flags ^ (1 << bit_to_toggle);

So HOW HARD it is to figure it out from the article I initially
pointed.

Also what about wikipedia?
http://en.wikipedia.org/wiki/Bitwise_operation

It wasn't about "Ok how do I set the most significant bit of an
integer" or anything tricky. It was a simple "how to toggle the Nth
bit" there wasn't anything about performance or so.

Now please tell me how big of an id**t you should be to go ahead and
ask this instead of doing some research first, eh? It is THAT SIMPLE:
int result = flags ^ (1 << bit_to_toggle);

If you can't even figure out that setting, clearing or toggling bits is
a bitwise operation and perform a descent search on google or yahoo and
filter out the crap from the good explanations then you DEFINITELY
should consider a carreer change. Or if you don't want to learn
anything but the immediate answer.

You think I'm too offensive, but what I want to achive is to make the
original poster ACTUALLY THINK. Answering a stupid question won't help
the guy/gal. Making him/her think will. So I will keep saying how
stupid this is until he/she realizes that, because asking basic stuff
without even bothering to check is really really STUPID.

Regards,
Nikolay
 
N

nsimeonov

Andre said:
You accuse Richard
Heathfield of not spending his time right correcting you over answering
the OP, while you yourself have done little to nothing to help out.

You didn't understand my point. Answering basic questions wouldn't help
the OP in any way. It will solve his/her immediate problem and will
just make him/her ask more stupid questions without even trying to
figure it out on it's own.

One day I had the same conversation with a guy who was attacking
someone just like I do now and he shared that he had a similar
experience before when he was a newbie. He said that his question was
something similar to "what temperature should I set the oven when
putting babies in it". He got a couple of "nice" or "yeah, right", one
answer telling him politely that it isn't the way and someone who
basically tearing him apart and telling him what an idiot he should be
to ask something like. And this last answer actually made him think, do
the research anf figure out how wrong he was. This guy made him think.

I don't really want to offend the OP. I want to make him/her actually
THINK. Being polite won't help here.
 
N

nsimeonov

Chris said:
Not much. Not for C programmers who want to learn C operators and C types.

Huh? We are talking about bitwise operators, didn't we? Looks like
something this guy/gal should read before posting his/her question.
 
R

Richard Heathfield

(e-mail address removed) said:
Ok. Do you like this one better?
http://www.codeproject.com/cpp/bitbashing.asp
No.

Why do we keep arguing?

Your aggressive response to the OP was over the top. Calling him stupid just
for asking a question is uncalled for. Hence my demonstration that your own
advice was flawed.
Bitwise operators are something VERY BASIC and
it's irrelevant to explain them on the newsgroups when you may find a
few nice articles for less than 5 minutes.

You just tried twice and failed twice, so it's not as easy as that after
all, is it?
Come on, BITWISE operators:
AND, OR, XOR, NOT - is there someone out there who is trying to program
and never heard of them. Multiplication on powers of 2 isn't so hard to
figure out if you ever heard of binary and hexadecimal numbers.

You are making the same mistake as the site you first cited - that of
confusing "number" and "representation".
If you
don't - well you either should consider a carreer change or read a book
about the basics.

I agree about the book. The OP would have been wise to consult K&R, which
explains this fully. As for the career change, has it occurred to you that
he might not have started on his career yet? People generally undergo a
period of study before embarking on a career, and at the time when they're
studying, them might not necessarily have decided yet what it is that they
want to do. Or perhaps they are simply studying the language for interest's
sake.
If you have so much time why didn't you answer the question

Because by the time I saw the question, Peter Nillson had already pointed
the OP to the FAQ. I saw no reason to duplicate that perfectly good answer.
and even
better - write an article and publish it on codeproject or your blog or
somewhere else so other newbies can find it?

I may do so one day, but for now it's way down on my to-do list because the
material is adequately covered in K&R and the FAQ.
 
A

Andre Reffhaug

You didn't understand my point. Answering basic questions wouldn't help
the OP in any way. It will solve his/her immediate problem and will
just make him/her ask more stupid questions without even trying to
figure it out on it's own.

You are not required to answer his basic questions, you are required to
act civil when denying to do so. There are plain words that can be
applied to the situation very accurately, without resorting to calling
people idiots and ignorants. The tough love approach is alright, but it
doesn't have to be so tough as to make yourself look like the fool.
One day I had the same conversation with a guy who was attacking
someone just like I do now and he shared that he had a similar
experience before when he was a newbie. He said that his question was
something similar to "what temperature should I set the oven when
putting babies in it". He got a couple of "nice" or "yeah, right", one
answer telling him politely that it isn't the way and someone who
basically tearing him apart and telling him what an idiot he should be
to ask something like. And this last answer actually made him think, do
the research anf figure out how wrong he was. This guy made him think.

Hearing that story wouldn't make me want to apply the formula to every
case I meet. Actually, I myself wouldn't apply the formula to any case
at all. There are many people that have taught me many a thing by
telling me that I have asked a dumb question, without also telling me
that I am an idiot and that I need to change my career and general
direction in life.
I don't really want to offend the OP. I want to make him/her actually
THINK. Being polite won't help here.

It just might. Being polite is not the same thing as being naively helpful.
 
R

Richard Heathfield

(e-mail address removed) said:
Besides about the original question the first site had a couple of code
snippets that one can use

Sure, if one is foolish enough to trust a site that makes so many STUPID
errors that anyone STUPID enough to recommend it is too STUPID to be a C
programmer and should consider a change in career.

So - what are you going to do next? Management? Marketing? Perhaps nursing?
Also what about wikipedia?

Democracy is a poor substitute for expertise.
 
E

Eric Sosman

Besides about the original question the first site had a couple of code
snippets that one can use :

int mult_by_pow_2(int number, int power)
{
return number<<power;
}

AGAIN?!!! Sheesh ...
 
R

Richard Heathfield

(e-mail address removed) said:
Huh? We are talking about bitwise operators, didn't we? Looks like
something this guy/gal should read before posting his/her question.

Let's look at something from that site, then, shall we?

----
BYTE b = 50;
BYTE c = b | 0x04;
cout << "c = " << c << endl;

This would result in the following calculation
00110010 - b
| 00000100 - | 0x04
----------
00110110 - result
----

Not only does the explanation assume that their (undefined) BYTE type is
synonymous with a byte (which, to be fair, it could be, using a typedef to
unsigned char), but it also assumes that a byte comprises only eight bits,
which is certainly false on some systems. It also completely fails to
mention the diagnostic message that a conforming implementation must issue
for the code fragment cited above.
 
P

pete

Hi,

Can anyone please tell me how to toggle a nth bit. For example, I am
having a variable which is of 8 bits. I want to toggle the nth bit.

I use this set of macros for dealing with the nth bit
of an unsigned:

#define READ_UBIT(U, N) ((U) >> (N) & 1u)
#define SET_UBIT(U, N) ((void)((U) |= 1u << (N)))
#define CLEAR_UBIT(U, N) ((void)((U) &= ~(1u << (N))))
#define FLIP_UBIT(U, N) ((void)((U) ^= 1u << (N)))

"Flip" means "toggle"
 
V

Vladimir Oka

You think I'm too offensive, but what I want to achive is to make the
original poster ACTUALLY THINK. Answering a stupid question won't help
the guy/gal. Making him/her think will. So I will keep saying how
stupid this is until he/she realizes that, because asking basic stuff
without even bothering to check is really really STUPID.

Too offensive, too LOUD, too ill-informed, too self-righteous, the list
goes on...

Bye.
 
C

Chris Dollin

Huh? We are talking about bitwise operators, didn't we? Looks like
something this guy/gal should read before posting his/her question.

Not if they want to learn /C/ operators and /C/ types. (The stuff about
the effects of the logical operations isn't too bad; it's just wrong for
C.)
 
F

Frederick Gotham

posted:
Hi,

Can anyone please tell me how to toggle a nth bit. For example, I am
having a variable which is of 8 bits. I want to toggle the nth bit.

Regards,
Santosh


void ToggleBit( char * const p, unsigned const bit_index )
{
*p ^= 1U << bit_index;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top