By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,389 Members | 1,844 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,389 IT Pros & Developers. It's quick & easy.

Program to toggle nth bit in C

P: n/a
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

Jun 20 '06 #1
Share this Question
Share on Google+
50 Replies


P: n/a
sk*****@gmail.com wrote:

Can anyone please tell me how to toggle a nth bit.


Try the FAQ...

http://c-faq.com/misc/bitmanip.html

--
Peter

Jun 20 '06 #2

P: n/a
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...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

sk*****@gmail.com написа:
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


Jun 20 '06 #3

P: n/a
ns*******@gmail.com 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...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.

--
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)
Jun 20 '06 #4

P: n/a
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?

Jun 20 '06 #5

P: n/a
ns*******@gmail.com wrote:
Ok. Do you like this one better?
http://www.codeproject.com/cpp/bitbashing.asp
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.

--
Andre Reffhaug
http://anakron.peadrop.com
(concatenate 'string "a" surname "@gmail.com")
Jun 20 '06 #6

P: n/a

Richard Heathfield wrote:
......


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

Jun 20 '06 #7

P: n/a
ns*******@gmail.com wrote:
Ok. Do you like this one better?
http://www.codeproject.com/cpp/bitbashing.asp


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

--
Chris "seeker" Dollin
"We did not have time to find out everything we wanted to know." /A Clash of Cymbals/

Jun 20 '06 #8

P: n/a

Andre Reffhaug wrote:
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.

Jun 20 '06 #9

P: n/a

Chris Dollin wrote:
ns*******@gmail.com wrote:
Ok. Do you like this one better?
http://www.codeproject.com/cpp/bitbashing.asp


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.

Jun 20 '06 #10

P: n/a
ns*******@gmail.com wrote:

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


"Wikipedia founder Jimmy 'Jimbo' Wales has warned students not to
refer to Wikipedia"
<http://www.theregister.co.uk/2006/06/15/wikipedia_can_damage_your_grades/>

Not to say it isn't a good resource, but if you don't have sufficient
research skills to spot inaccuracies then Wikipedia can be dangerous.

--
imalone
Jun 20 '06 #11

P: n/a
ns*******@gmail.com 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.

--
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)
Jun 20 '06 #12

P: n/a
ns*******@gmail.com wrote:
Andre Reffhaug wrote:
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.


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.
--
Andre Reffhaug
http://anakron.peadrop.com
(concatenate 'string "a" surname "@gmail.com")
Jun 20 '06 #13

P: n/a
ns*******@gmail.com 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.

--
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)
Jun 20 '06 #14

P: n/a
ns*******@gmail.com wrote:
Richard Heathfield wrote:
......

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 ...

--
Eric Sosman
es*****@acm-dot-org.invalid
Jun 20 '06 #15

P: n/a
ns*******@gmail.com said:

Chris Dollin wrote:
ns*******@gmail.com wrote:
> Ok. Do you like this one better?
> http://www.codeproject.com/cpp/bitbashing.asp


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.


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.

--
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)
Jun 20 '06 #16

P: n/a
sk*****@gmail.com wrote:

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"

--
pete
Jun 20 '06 #17

P: n/a

ns*******@gmail.com wrote:
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.

Jun 20 '06 #18

P: n/a
ns*******@gmail.com wrote:
Chris Dollin wrote:
ns*******@gmail.com wrote:
> Ok. Do you like this one better?
> http://www.codeproject.com/cpp/bitbashing.asp


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.


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.)

--
Chris "seeker" Dollin
"I'm still here and I'm holding the answers" - Karnataka, /Love and Affection/

Jun 20 '06 #19

P: n/a
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;
}
--

Frederick Gotham
Jun 20 '06 #20

P: n/a
On 2006-06-20, sk*****@gmail.com <sk*****@gmail.com> wrote:
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.


var ^= (1U << n);

should do it

Sometimes you see flags done like this:

uint32_t set_flags(uint32_t flags, uint32_t clear, uint32_t xor)
{
return (flags & ~clear) ^ xor;
}

This odd-looking function allows you to set, toggle and clear any
combination of flags in one go, as the example below illustrates a bit.

Whether this is more or less confusing I'm not sure... it's quite good
in APIs, though, where the fact that flags are stored as bits is not
necessarily exposed to the caller.

#include <stdio.h>
#include <stdint.h>

uint32_t set_flags(uint32_t flags, uint32_t clear, uint32_t xor)
{
return (flags & ~clear) ^ xor;
}

#define APPLES 1U
#define PEARS 1U << 1
#define ORANGES 1U << 2
#define BANANAS 1U << 3

void print_flags(uint32_t flags)
{
if (flags & APPLES) printf("APPLES\n");
if (flags & PEARS) printf("PEARS\n");
if (flags & ORANGES) printf("ORANGES\n");
if (flags & BANANAS) printf("BANANAS\n");
printf("\n");
}

int main(void)
{
uint32_t flags = APPLES | ORANGES;
print_flags(flags);

/* set PEARS */
flags = set_flags(flags, PEARS, PEARS);
print_flags(flags);

/* clear PEARS */
flags = set_flags(flags, PEARS, 0);
print_flags(flags);

/* toggle PEARS a couple of times */
flags = set_flags(flags, 0, PEARS);
print_flags(flags);
flags = set_flags(flags, 0, PEARS);
print_flags(flags);

/*
* set BANANAS, toggle PEARS and APPLES, and clear ORANGES, all in one go
*/
flags = set_flags(flags, ORANGES | BANANAS, BANANAS | PEARS | APPLES);
print_flags(flags);

return 0;
}
Jun 20 '06 #21

P: n/a
Ben C said:

<snip>
#include <stdio.h>
#include <stdint.h>

uint32_t set_flags(uint32_t flags, uint32_t clear, uint32_t xor)
{
return (flags & ~clear) ^ xor;
}


Careful. This code can be broken by the inclusion of <iso646.h>, because of
the xor identifier.

--
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)
Jun 20 '06 #22

P: n/a
Richard Heathfield wrote:
ns*******@gmail.com said:
Chris Dollin wrote:
ns*******@gmail.com wrote:

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

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.


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.


Which also does some very peculiar shift operations for the C
language. I have no idea whether left shifts are evaluated left to
right or right to left, nor do I intend to bother to find out. The
values of cout and endl are also undefined.

--
"I don't know where bin Laden is. I have no idea and really
don't care. It's not that important." - G.W. Bush, 2002-03-13
"No, we've had no evidence that Saddam Hussein was involved
with September the 11th." - George Walker Bush 2003-09-17
Jun 20 '06 #23

P: n/a
I'm amazed how much efforts you guys put to answer this simple question
and defend the original poster. I was in a bad mood this morning and
that's why I answered initially, nevertheless I would be happier to see
answers to the real questions where you can't find the answer by
googling for 10 min or so.

Regards and I hope the OP actually understood the point I was making,
Nikolay

Jun 20 '06 #24

P: n/a
ns*******@gmail.com said:
I'm amazed how much efforts you guys put to answer this simple question
and defend the original poster.
Had you not attacked him, we would not have felt obliged to defend him. Your
attack was unwarranted and ugly.
I was in a bad mood this morning and that's why I answered initially,
Then you might want to give some consideration to the idea of waiting until
you are in a good mood before answering questions.
nevertheless I would be happier to see
answers to the real questions where you can't find the answer by
googling for 10 min or so.
We answer what gets asked. If the question is answered in the FAQ or in K&R
we will generally point the questioner in that direction. It is possible to
do this without calling him stupid.
Regards and I hope the OP actually understood the point I was making,


Presumably you mean this point: "I'm tempted to suggest you a carreer change
or plainly tell you how big of an id**t you are."

Yes, I think it would be quite difficult to misunderstand that point,
despite the appalling spelling and grammar.

If you meant the rest of your article, including that ridiculously broken
Web site you recommended, I've already dealt with that elsethread.

--
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)
Jun 20 '06 #25

P: n/a
In article <11*********************@p79g2000cwp.googlegroups. com>,
<sk*****@gmail.com> wrote:
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.


Which bit is the nth bit? Does the numbering start from 0 or 1?
Is the ordering left to right or right to left? Is the variable
signed or unsigned?

You should keep in mind that variables may contain padding bits and that
there might be a seperate sign bit which is not arithmetically accessible.
For example, setting the "8th" (most significant) bit of an unsigned char
is not necessarily going to result in a bit representation that
would indicate a negative number of reinterpreted as a signed value.
--
Programming is what happens while you're busy making other plans.
Jun 20 '06 #26

P: n/a
On 2006-06-20, Richard Heathfield <in*****@invalid.invalid> wrote:
Ben C said:

<snip>
#include <stdio.h>
#include <stdint.h>

uint32_t set_flags(uint32_t flags, uint32_t clear, uint32_t xor)
{
return (flags & ~clear) ^ xor;
}


Careful. This code can be broken by the inclusion of <iso646.h>, because of
the xor identifier.


Good point! Maybe it's time I changed my syntax file to highlight those
things.

I did know you could use "and" and "or" etc. in C++, where I think they
may be part of the actual language syntax, not macros, but I'd not heard
of this iso646 thing.
Jun 20 '06 #27

P: n/a
Walter Roberson posted:
In article <11*********************@p79g2000cwp.googlegroups. com>,
<sk*****@gmail.com> wrote:
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.
Which bit is the nth bit? Does the numbering start from 0 or 1?

We're dealing with computers, so 0.

Is the ordering left to right or right to left? Is the variable
signed or unsigned?

An educated guess would be that the bist are indexed in ascending order,
starting with the least significant bit.

You should keep in mind that variables may contain padding bits

Unsigned integer types don't contain padding. They may however contain
trapping bits, which are bits which do not take part in the value
representation of the object.

and
that there might be a seperate sign bit which is not arithmetically
accessible.

I would have thought that there be some sort of requirement that the
signed and unsigned forms of a particular integer type have the same
amount of value representation bits... but it looks like "signed char"
can have trapping bits. (In C++, signed char cannot have trapping bits).
Well, if signed char couldn't have trapping bits in C, then the following
would be true:
(Assuming CHAR_BIT == 8)

unsigned char uc = 133;

signed char c = *( (signed char*)&uc );
Then depending on the negative number system in use, "c" can have one of
three values:

Sign-magnitude: -5
One's complement: 122
Two's complement: 123
--

Frederick Gotham
Jun 20 '06 #28

P: n/a
Frederick Gotham posted:

Sign-magnitude: -5
One's complement: 122
Two's complement: 123

I left out the negative signs:
Sign-magnitude: -5
One's complement: -122
Two's complement: -123
--

Frederick Gotham
Jun 20 '06 #29

P: n/a
Frederick Gotham wrote:
Unsigned integer types don't contain padding.


N869
6.2.6.2 Integer types
[#1] For unsigned integer types other than unsigned char,
the bits of the object representation shall be divided into
two groups: value bits and padding bits (there need not be
any of the latter).

--
pete
Jun 21 '06 #30

P: n/a
pete posted:
Frederick Gotham wrote:
Unsigned integer types don't contain padding.


N869
6.2.6.2 Integer types
[#1] For unsigned integer types other than unsigned char,
the bits of the object representation shall be divided into
two groups: value bits and padding bits (there need not be
any of the latter).

Okay, so they contain padding.

My understanding was that padding is required so that a type's alignment
requirements can be satisfied -- I didn't think the term extended to refer
to the "extra bits" in an unsigned integer type. Anyway I stand corrected.

Would anyone like to offer an explanation as to why an unsigned integer
type would need "padding" within it? At the moment I don't see a reason.

--

Frederick Gotham
Jun 21 '06 #31

P: n/a
Frederick Gotham <fg*******@SPAM.com> writes:
[...]
Would anyone like to offer an explanation as to why an unsigned integer
type would need "padding" within it? At the moment I don't see a reason.


I posted an example elsewhere in this thread. The machine in
question, as I understand it, happens to have instructions that work
on a subset of the bits of a word. (The machine's design strongly
emphasizes floating-point performance; it's a Cray Y-MP.)

--
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.
Jun 21 '06 #32

P: n/a
Keith Thompson <ks***@mib.org> writes:
Frederick Gotham <fg*******@SPAM.com> writes:
[...]
Would anyone like to offer an explanation as to why an unsigned integer
type would need "padding" within it? At the moment I don't see a reason.


I posted an example elsewhere in this thread. The machine in
question, as I understand it, happens to have instructions that work
on a subset of the bits of a word. (The machine's design strongly
emphasizes floating-point performance; it's a Cray Y-MP.)


Correction: the example was in the "FAQ-Question" thread.

--
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.
Jun 21 '06 #33

P: n/a
Frederick Gotham wrote:
.... snip ...
Would anyone like to offer an explanation as to why an unsigned
integer type would need "padding" within it? At the moment I don't
see a reason.


Just as a couple of examples, to detect uninitialized values, or to
provide ECC correction of values.

--
"I don't know where bin Laden is. I have no idea and really
don't care. It's not that important." - G.W. Bush, 2002-03-13
"No, we've had no evidence that Saddam Hussein was involved
with September the 11th." - George Walker Bush 2003-09-17
Jun 21 '06 #34

P: n/a
Frederick Gotham wrote:
void ToggleBit( char * const p, unsigned const bit_index )
{
*p ^= 1U << bit_index;
}


Toggling the sign bit could cause a trap representation;
you should use unsigned types when maniplating bits.

Jun 21 '06 #35

P: n/a
ns*******@gmail.com wrote:

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

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


Maybe you should consider a career change (unless you
are a drill sergeant or something).

Jun 21 '06 #36

P: n/a
sk*****@gmail.com wrote:
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


Look up Exclusive OR
Jun 21 '06 #37

P: n/a
"Neil" writes:
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


Look up Exclusive OR


And by just what mystical process is Santosh supposed to know that he should
read a new message that sprouts up with the message title "XOR"?

If he had been reading *all* the messages, for a few days he probably
wouldn't have had any need to post the question he asked in the first place.
Jun 21 '06 #38

P: n/a
In article <Xn**************************@194.125.133.14>,
Frederick Gotham <fg*******@SPAM.com> wrote:
Walter Roberson posted:
In article <11*********************@p79g2000cwp.googlegroups. com>,
<sk*****@gmail.com> wrote:
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.
Which bit is the nth bit? Does the numbering start from 0 or 1? We're dealing with computers, so 0.
The OP asked about the "nth" bit. "nth" is an expression indicating
an ordinal number, and ordinal numbers start with 1 -- 1st,
2nd, 3rd, 4th, etc..
Is the ordering left to right or right to left? Is the variable
signed or unsigned? An educated guess would be that the bist are indexed in ascending order,
starting with the least significant bit.
One could make that "educated guess", yes, but it does not necessarily
match the OP's requirements, as there are important processors that number
the bits the other way around.

You should keep in mind that variables may contain padding bits

Unsigned integer types don't contain padding.
Someone else already quoted the standard on this.

I would have thought that there be some sort of requirement that the
signed and unsigned forms of a particular integer type have the same
amount of value representation bits... but it looks like "signed char"
can have trapping bits. (In C++, signed char cannot have trapping bits).


The OP wasn't particularily firm on the point of the value being
8 bits wide, so it seemed likely to me that the OP would want to
generalize to wider types that do not have the exemptions that
various char might have.
--
Okay, buzzwords only. Two syllables, tops. -- Laurie Anderson
Jun 21 '06 #39

P: n/a
Old Wolf posted:
Frederick Gotham wrote:
void ToggleBit( char * const p, unsigned const bit_index )
{
*p ^= 1U << bit_index;
}


Toggling the sign bit could cause a trap representation;
you should use unsigned types when maniplating bits.

You're right. Got to get out of my C++ habit of using char all the time
rather than unsigned char. Give me a slap if I do it again!
Jun 21 '06 #40

P: n/a
Frederick Gotham <fg*******@SPAM.com> writes:
Old Wolf posted:
Frederick Gotham wrote:
void ToggleBit( char * const p, unsigned const bit_index )
{
*p ^= 1U << bit_index;
}


Toggling the sign bit could cause a trap representation;
you should use unsigned types when maniplating bits.

You're right. Got to get out of my C++ habit of using char all the time
rather than unsigned char. Give me a slap if I do it again!


<OT>
Why is that a C++ habit? C++ has the same rules for plain char as C
does.
</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.
Jun 21 '06 #41

P: n/a
On Tue, 20 Jun 2006 23:09:19 GMT, in comp.lang.c , Frederick Gotham
<fg*******@SPAM.com> wrote:
Walter Roberson posted:
Which bit is the nth bit? Does the numbering start from 0 or 1?


We're dealing with computers, so 0.


Apparently you don't use Fortran, Pascal or Basic... :-)

Also is the first bit the LSB or MSB?

--
Mark McIntyre

"Debugging is twice as hard as writing the code in the first place.
Therefore, if you write the code as cleverly as possible, you are,
by definition, not smart enough to debug it."
--Brian Kernighan
Jun 21 '06 #42

P: n/a
On 2006-06-21, Mark McIntyre <ma**********@spamcop.net> wrote:
On Tue, 20 Jun 2006 23:09:19 GMT, in comp.lang.c , Frederick Gotham
<fg*******@SPAM.com> wrote:
Walter Roberson posted:
Which bit is the nth bit? Does the numbering start from 0 or 1?


We're dealing with computers, so 0.


Apparently you don't use Fortran, Pascal or Basic... :-)

Also is the first bit the LSB or MSB?


The first bit is the rightmost. How this is used by the system
doesn't really matter, but for simplicity's sake, bits will be
labelled as such (in hexadecimal): FEDCBA98 76543210

The reason for this is that starting from anywhere other than
the right would require knowing the size of the type beforehand,
which complicates macros, however slightly.

--
Andrew Poelstra < http://www.wpsoftware.net/blog >
To email me, use "apoelstra" at the above address.
I know that area of town like the back of my head.
Jun 21 '06 #43

P: n/a
On Wed, 21 Jun 2006 23:19:53 GMT, Andrew Poelstra
<ap*******@localhost.localdomain> wrote:
On 2006-06-21, Mark McIntyre <ma**********@spamcop.net> wrote:
On Tue, 20 Jun 2006 23:09:19 GMT, in comp.lang.c , Frederick Gotham
<fg*******@SPAM.com> wrote:
Walter Roberson posted:

Which bit is the nth bit? Does the numbering start from 0 or 1?

We're dealing with computers, so 0.


Apparently you don't use Fortran, Pascal or Basic... :-)

Also is the first bit the LSB or MSB?


The first bit is the rightmost. How this is used by the system
doesn't really matter, but for simplicity's sake, bits will be
labelled as such (in hexadecimal): FEDCBA98 76543210

The reason for this is that starting from anywhere other than
the right would require knowing the size of the type beforehand,
which complicates macros, however slightly.


The limitations of your experience are showing. The largest publisher
of computing documentation labels the left most bit as bit 0.
Remove del for email
Jun 22 '06 #44

P: n/a
On 2006-06-22, Barry Schwarz <sc******@doezl.net> wrote:
On Wed, 21 Jun 2006 23:19:53 GMT, Andrew Poelstra
<ap*******@localhost.localdomain> wrote:
On 2006-06-21, Mark McIntyre <ma**********@spamcop.net> wrote:
On Tue, 20 Jun 2006 23:09:19 GMT, in comp.lang.c , Frederick Gotham
<fg*******@SPAM.com> wrote:

Walter Roberson posted:

> Which bit is the nth bit? Does the numbering start from 0 or 1?

We're dealing with computers, so 0.

Apparently you don't use Fortran, Pascal or Basic... :-)

Also is the first bit the LSB or MSB?


The first bit is the rightmost. How this is used by the system
doesn't really matter, but for simplicity's sake, bits will be
labelled as such (in hexadecimal): FEDCBA98 76543210

The reason for this is that starting from anywhere other than
the right would require knowing the size of the type beforehand,
which complicates macros, however slightly.


The limitations of your experience are showing. The largest publisher
of computing documentation labels the left most bit as bit 0.


I know that; I did spent a year learning Intel assembly language.
However, as far as quick C programs go, it's easiest to do the
reverse. That way, bit 0 of a char will be the same as bit 0 of
an int. (I'm assuming that sizeof (char) != sizeof(int) here).

--
Andrew Poelstra < http://www.wpsoftware.net/blog >
To email me, use "apoelstra" at the above address.
I know that area of town like the back of my head.
Jun 22 '06 #45

P: n/a
In article <sl**********************@localhost.localdomain> ,
Andrew Poelstra <ap*******@localhost.localdomain> wrote:
On 2006-06-22, Barry Schwarz <sc******@doezl.net> wrote:
On Wed, 21 Jun 2006 23:19:53 GMT, Andrew Poelstra
<ap*******@localhost.localdomain> wrote:
On 2006-06-21, Mark McIntyre <ma**********@spamcop.net> wrote:
On Tue, 20 Jun 2006 23:09:19 GMT, in comp.lang.c , Frederick Gotham
<fg*******@SPAM.com> wrote:Walter Roberson posted: Which bit is the nth bit? Does the numbering start from 0 or 1?
The limitations of your experience are showing. The largest publisher
of computing documentation labels the left most bit as bit 0.
I know that; I did spent a year learning Intel assembly language.
However, as far as quick C programs go, it's easiest to do the
reverse.


Andrew, you admit that are multiple valid definitions of which bit is
numbered 0, so why are you attempting to provide a definitive answer as
to what bit numbering system the original poster intended? Leave it
to the original poster to clarify exactly what the original
poster is trying to ask.
--
All is vanity. -- Ecclesiastes
Jun 22 '06 #46

P: n/a
On Thu, 22 Jun 2006 02:19:01 GMT, Andrew Poelstra
<ap*******@localhost.localdomain> wrote:
On 2006-06-22, Barry Schwarz <sc******@doezl.net> wrote:
On Wed, 21 Jun 2006 23:19:53 GMT, Andrew Poelstra
<ap*******@localhost.localdomain> wrote:
On 2006-06-21, Mark McIntyre <ma**********@spamcop.net> wrote:
On Tue, 20 Jun 2006 23:09:19 GMT, in comp.lang.c , Frederick Gotham
<fg*******@SPAM.com> wrote:

>Walter Roberson posted:
>
>> Which bit is the nth bit? Does the numbering start from 0 or 1?
>
>We're dealing with computers, so 0.

Apparently you don't use Fortran, Pascal or Basic... :-)

Also is the first bit the LSB or MSB?
The first bit is the rightmost. How this is used by the system
doesn't really matter, but for simplicity's sake, bits will be
labelled as such (in hexadecimal): FEDCBA98 76543210

The reason for this is that starting from anywhere other than
the right would require knowing the size of the type beforehand,
which complicates macros, however slightly.


The limitations of your experience are showing. The largest publisher
of computing documentation labels the left most bit as bit 0.


I know that; I did spent a year learning Intel assembly language.
However, as far as quick C programs go, it's easiest to do the
reverse. That way, bit 0 of a char will be the same as bit 0 of
an int. (I'm assuming that sizeof (char) != sizeof(int) here).


It is not Intel, though the first letter is correct.
Remove del for email
Jun 22 '06 #47

P: n/a
Andrew Poelstra (in sl**********************@localhost.localdomain)
said:

| On 2006-06-22, Barry Schwarz <sc******@doezl.net> wrote:
||
|| The limitations of your experience are showing. The largest
|| publisher of computing documentation labels the left most bit as
|| bit 0.
|
| I know that; I did spent a year learning Intel assembly language.
| However, as far as quick C programs go, it's easiest to do the
| reverse. That way, bit 0 of a char will be the same as bit 0 of
| an int. (I'm assuming that sizeof (char) != sizeof(int) here).

I think Barry is referring to the NIH (Not Invented Here) maniacs who
seemed to think that calling the LSB "bit 0" was a bit too obvious -
so they chose a reversed bit numbering scheme that disassociated the
bit number from the power of two it represented.

On the other hand, they did gift the world with EBCDIC and a whole
assortment of other artful encoding creations. :-)

--
Morris Dovey
DeSoto Solar
DeSoto, Iowa USA
http://www.iedu.com/DeSoto
Jun 22 '06 #48

P: n/a
Keith Thompson posted:

You're right. Got to get out of my C++ habit of using char all the time rather than unsigned char. Give me a slap if I do it again!


<OT>
Why is that a C++ habit? C++ has the same rules for plain char as C
does.
</OT>

In C++, signed char is guaranteed to have no "invalid values" (just like
the situation is for unsigned char in C). The following is perfectly
legal in C++, but non-portable in C:
int main(void)
{
unsigned i = 58; /* Or any arbitrary value */
char *p = (char*)&i;

const char * const p_over = (const char*)(&i + 1);
do
{
*p++ += 3;
} while ( p != p_over );
}
Therefore, in C++, it's perfectly safe to access any object as if it were
an array of char's.

When writing C code, I have to make sure that I access the bytes as
unsigned char's, rather than just plain char.

Jun 22 '06 #49

P: n/a
Morris Dovey wrote:
.... snip ...
I think Barry is referring to the NIH (Not Invented Here) maniacs
who seemed to think that calling the LSB "bit 0" was a bit too
obvious - so they chose a reversed bit numbering scheme that
disassociated the bit number from the power of two it represented.

On the other hand, they did gift the world with EBCDIC and a whole
assortment of other artful encoding creations. :-)


OTOH on a machine with the more significant bytes in the lower
addresses (which is either big or little endian :-) this convention
eases generic addressing of individual bits. When bytes are also
sized to a power of two, the bit/byte addresses can be extracted
with simple masks.

--
"I don't know where bin Laden is. I have no idea and really
don't care. It's not that important." - G.W. Bush, 2002-03-13
"No, we've had no evidence that Saddam Hussein was involved
with September the 11th." - George Walker Bush 2003-09-17
Jun 22 '06 #50

50 Replies

This discussion thread is closed

Replies have been disabled for this discussion.