473,407 Members | 2,315 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,407 software developers and data experts.

Bitwise operator question...

I'm trying to figure out this question i was asked but am having no luck!
here's the question:

"Write a Program that swaps the contents of two variables without
using any other variable. Use one of the bitwise operators."

I'm clueless... Any help would be appreciated!

Thanks.
Jul 19 '05 #1
10 8203
On Tue, 30 Sep 2003 02:57:36 GMT, "littlehobo" <Li********@tack.com>
wrote in comp.lang.c++:
I'm trying to figure out this question i was asked but am having no luck!
here's the question:

"Write a Program that swaps the contents of two variables without
using any other variable. Use one of the bitwise operators."

I'm clueless... Any help would be appreciated!

Thanks.


Don't bother, it a crap question. There is no way to do this that is
guaranteed not to invoke undefined behavior. People who ask questions
like this don't know nearly as much about real C or C++ as they think.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++ ftp://snurse-l.org/pub/acllc-c++/faq
Jul 19 '05 #2
Jack Klein wrote:
On Tue, 30 Sep 2003 02:57:36 GMT, "littlehobo" <Li********@tack.com>
wrote in comp.lang.c++:

I'm trying to figure out this question i was asked but am having no luck!
here's the question:

"Write a Program that swaps the contents of two variables without
using any other variable. Use one of the bitwise operators."

I'm clueless... Any help would be appreciated!

Thanks.

CLUE: You want the ^ operator.

Don't bother, it a crap question. There is no way to do this that is
guaranteed not to invoke undefined behavior. People who ask questions
like this don't know nearly as much about real C or C++ as they think.


What undefined behavior? This type of thing is used (or was at one
time) a lot in graphics programming. I would be very interested in
knowing what kind of unexpected behavior you could get from this technique.

NR

Jul 19 '05 #3
Thanks, for the replys! It took me a while...probably because I originally
thought I was supposed to do it with one expression...I guess I was reading
it "use one bitwise operator" or something. Anyway this is what I came up
with:

int a = 5, b = 8; //or whatever variables
a ^= b;
b ^= a;
a ^= b;

that took some time and paper lol!
Jul 19 '05 #4
[..]
int a = 5, b = 8; //or whatever variables
a ^= b;
b ^= a;
a ^= b;

that took some time and paper lol!


Well, I am not using bit operators, but the rule of associativity.

a = (b+b)/2 + ((b=a)-a);
--
Vijay Kumar R Zanvar
Jul 19 '05 #5
"littlehobo" <Li********@tack.com> wrote in message news:<3f**********************@news.astraweb.com>. ..
I'm trying to figure out this question i was asked but am having no luck!
here's the question:

"Write a Program that swaps the contents of two variables without
using any other variable. Use one of the bitwise operators."

I'm clueless... Any help would be appreciated!

Thanks.


Use this fact " (a^b)^a = b, (a^b)^b = a "
Jul 19 '05 #6
In article <bl************@ID-203837.news.uni-berlin.de>,
vi*****@hotmail.com says...

[ ... ]
Well, I am not using bit operators, but the rule of associativity.

a = (b+b)/2 + ((b=a)-a);


....and the nasal demons rear their ugly heads just like they do every
time this subject arises.

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jul 19 '05 #7
On Mon, 29 Sep 2003 21:18:07 -0700, Noah Roberts
<nr******@dontemailme.com> wrote in comp.lang.c++:
Jack Klein wrote:
On Tue, 30 Sep 2003 02:57:36 GMT, "littlehobo" <Li********@tack.com>
wrote in comp.lang.c++:

I'm trying to figure out this question i was asked but am having no luck!
here's the question:

"Write a Program that swaps the contents of two variables without
using any other variable. Use one of the bitwise operators."

I'm clueless... Any help would be appreciated!

Thanks.


CLUE: You want the ^ operator.


Don't bother, it a crap question. There is no way to do this that is
guaranteed not to invoke undefined behavior. People who ask questions
like this don't know nearly as much about real C or C++ as they think.


What undefined behavior? This type of thing is used (or was at one
time) a lot in graphics programming. I would be very interested in
knowing what kind of unexpected behavior you could get from this technique.

NR


Case 1:

double d1 = 3.14159;
double d2 = 3.6864;

double swap_contents_with_bitwise_operators(double d1, double d2)
{
double result = /* please fill in the blank */ ;
return result;
}

Case 2:

int swap_ints(int *a, int *b)
{
*a ^= *b;
*b ^= *a;
}

Above can generate a trap representation, hence undefined behavior.
But what about unsigned ints, you say?

Consider the function above and...

int x = 27;
swap(&x, &x);

....not to mention that anyone who wrote this in production would be
shot on sight. Well, OK, at the code inspection.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++ ftp://snurse-l.org/pub/acllc-c++/faq
Jul 19 '05 #8
On Mon, 29 Sep 2003 21:18:07 -0700, Noah Roberts
<nr******@dontemailme.com> wrote in comp.lang.c++:
Jack Klein wrote:
On Tue, 30 Sep 2003 02:57:36 GMT, "littlehobo" <Li********@tack.com>
wrote in comp.lang.c++:

I'm trying to figure out this question i was asked but am having no luck!
here's the question:

"Write a Program that swaps the contents of two variables without
using any other variable. Use one of the bitwise operators."

I'm clueless... Any help would be appreciated!

Thanks.


CLUE: You want the ^ operator.


Don't bother, it a crap question. There is no way to do this that is
guaranteed not to invoke undefined behavior. People who ask questions
like this don't know nearly as much about real C or C++ as they think.


What undefined behavior? This type of thing is used (or was at one
time) a lot in graphics programming. I would be very interested in
knowing what kind of unexpected behavior you could get from this technique.

NR


Case 1:

double d1 = 3.14159;
double d2 = 3.6864;

double swap_contents_with_bitwise_operators(double d1, double d2)
{
double result = /* please fill in the blank */ ;
return result;
}

Case 2:

int swap_ints(int *a, int *b)
{
*a ^= *b;
*b ^= *a;
}

Above can generate a trap representation, hence undefined behavior.
But what about unsigned ints, you say?

Consider the function above and...

int x = 27;
swap(&x, &x);

....not to mention that anyone who wrote this in production would be
shot on sight. Well, OK, at the code inspection.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++ ftp://snurse-l.org/pub/acllc-c++/faq
Jul 19 '05 #9
Jack Klein wrote:
On Mon, 29 Sep 2003 21:18:07 -0700, Noah Roberts
<nr******@dontemailme.com> wrote in comp.lang.c++:
What undefined behavior? This type of thing is used (or was at one
time) a lot in graphics programming. I would be very interested in
knowing what kind of unexpected behavior you could get from this technique.

NR

Case 1:

double d1 = 3.14159;
double d2 = 3.6864;

double swap_contents_with_bitwise_operators(double d1, double d2)
{
double result = /* please fill in the blank */ ;
return result;
}


I was pretty sure this was the case but I tested it anyway:

test.cpp:11: error: invalid operands of types `double' and `double' to
binary `
operator^'
test.cpp:11: error: in evaluation of `operator^=(double, double)'
and more of the same...

Correct me if my compiler is non-standard. I think C would barf also.

Yes, there is probably a good reason why bitwise operators are not
allowed on floating point types.

Case 2:

int swap_ints(int *a, int *b)
{
*a ^= *b;
*b ^= *a;
}
Yes, you never ever want to do that.....
int x = 27;
swap(&x, &x);
because the pointers might point to the same thing. This also would be
undefined:

x ^= x;

or
x += x; // yet you won't be saying += is a bad operation...

I believe even 'x = x' is undefined.

However, this sort of code is completely safe and quite useful:

int x = 27, y = 34;
x ^= y; y ^= x; x ^= y; // We know what x and y are after this...

For instance, the easiest fastest way to highlight text in a GUI is to
to use xor operators. You can also quickly switch colors with an xor
operation as used in computer games (maybe not anymore):

some_integral_type color_key = what_i_want ^ what_is_there;

xor_draw_area(area, color_key); // switch
xor_draw_area(area, color_key); // switch back.

Also, you can make your function safe:

void swap(int *x, int *y)
{
if (x==y) return; // no need to swap and it would be undefined if we
did...

... // but it is safe otherwise...(assuming we own the memory
pointed to by x and y which you also want to check).
}

...not to mention that anyone who wrote this in production would be
shot on sight. Well, OK, at the code inspection.


Nobody really uses it to swap value x and y, but often you want to
quickly change and revert values and xor is a great way to do that. It
is used a lot in XFree86 and probably just about any GUI system around.

NR

Jul 19 '05 #10

"Jack Klein" <ja*******@spamcop.net> wrote in message news:q4********************************@4ax.com...

int x = 27;
swap(&x, &x);

...not to mention that anyone who wrote this in production would be
shot on sight. Well, OK, at the code inspection.


And for practical matters if you look at the code generated by most compilers for
template <class T> inline void swap(T& a, T& b) {
T t = a;
a = b;
b = t;
}
You'll find it involves fewer operations than the xor-hack. If T fits in a register
it may not even involve an explicit temporary just the registers needed for
the assignments:

R1 <- a
R2 <- b
b <- R1
a <- R2

Jul 19 '05 #11

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

Similar topics

11
by: Randell D. | last post by:
Why would one use bitwise operators? I can program in various languages in some shape or form (C++, PHP, some scripting) and I've heard/seen bitwise operators before, but never understood why...
34
by: Christopher Benson-Manica | last post by:
I'm trying to compute the absolute value of an integer using only bitwise operators... int x; sscanf( "%d", &x ); printf( "%d\n", (x^((~((x>>31)&1))+1)) + ((x>>31)&1) ); That works, but it...
13
by: Manish_Ganvir | last post by:
Please do not use pointer arithmetic or for loops Solution
2
by: Steve Summit | last post by:
-----BEGIN PGP SIGNED MESSAGE----- It's often explained that the reason for some of the imprecision in C's definition is so that C can be implemented on different kinds of machines -- say, those...
9
by: Christopher Weaver | last post by:
I know that the bitwise AND of 8 and 4 will return 0 or false and the bitwise AND of 8 and 9 will return 1 or true but I don't know how to write the synax for it in C#. I have a value that ranges...
5
by: Bill Dee | last post by:
I need help converting a tiny piece of code which uses the bitwise complement operator from C# to VB.NET. In C# I currently have this: long useThis = Myclass.ALLCONSTANTS; long doNotUse =...
10
by: David R. | last post by:
I want to do bitwise operation on some large integers. For example, Response.Write CBool(2 AND 2^30) ' returns False Response.Write CBool(2 AND 2^31) ' CRASHED! Looks like the AND...
3
by: Marc | last post by:
I'm trying to set the first three bits to zero on a byte. For some reason, the compiler is casting the number peculiarly when I use the bitwise complement operator. Here's what I think should...
2
by: Mark Rae | last post by:
Hi, This isn't *specifically* an ASP.NET question, so I've also posted it in the ADO.NET group - however, it's not too far off-topic... Imagine a SQL Server 2005 database with a table with an...
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...
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
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...
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...
0
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,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.