Switching byte values between variables

This is a discussion on Switching byte values between variables within the C++ Programming forums, part of the General Programming Boards category; Hey guys, I thought some of you might find this trick useful. say you have 2 integers int a = ...

  1. #1
    Registered User
    Join Date
    Jul 2002
    Posts
    47

    Switching byte values between variables

    Hey guys,
    I thought some of you might find this trick useful.

    say you have 2 integers
    int a = 5;
    int b = 3;
    Say you need to switch these variables so that a = b and b=a.
    Most people would od it such that
    Code:
    int a=5;
    int b=3;
    int c;
    c=a;
    a=b;
    b=c;
    However, there is a way to do this in which a third variable is not needed.
    Code:
    int a=5;
    int b=3;
    a ^= b;
    b ^= a;
    a ^= b;
    That's it.
    You just successfully switched the values of a and b without a third variable. Thank God for Boolean Logic :-D

    Note: This was done using integers but it could also be done using any data type including characters and structs because this command does not really care. All it cares about is the binary data.

  2. #2
    Slave MadCow257's Avatar
    Join Date
    Jan 2005
    Posts
    735
    Interesting, however I don't think that will work with structs. If so, can you give me an example? I tried this
    Code:
    #include <iostream>
    
    using std::cout;
    
    int main()
    {
    	struct Test
    	{
    		int test1;
    		int test2;
    	}a, b;
    	a.test1 = 15;
    	a.test2 = 17;
    	b.test1 = 16;
    	b.test1 = 18;
    	a ^= b;
    	b ^= a;
    	a ^= b;
    	cout << a.test1 << "\n";
    	cout << b.test1 << "\n";
    	cout << a.test2 << "\n";
    	cout << b.test2 << "\n";
    	return 0;
    }
    However I made it in like 30 seconds so something may be wrong with it.
    It gives three errors,
    "error C2676: binary '^=' : 'struct main::Test' does not define this operator or a conversion to a type acceptable to the predefined operator"

  3. #3
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,794
    This keeps popping up every now and again on this board:

    swaping numbers
    swapping
    Why ^ will swap values?

    Swapping using XOR should only be applied to integer types.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  4. #4
    Registered User
    Join Date
    Jul 2002
    Posts
    47
    yea, im having difficulty with structs as well, but am looking into it by making the compiler thing of it as a different type. I've seen character types work. particularly unsigned characters.

  5. #5
    Registered User
    Join Date
    Jan 2005
    Posts
    181
    Code:
    originally posted by MadCow257 
    
    Interesting, however I don't think that will work with structs. If so, can you give me an example? I tried this
    
    Code:
    #include <iostream>
    
    using std::cout;
    
    int main()
    {
        struct Test
        {
            int test1;
            int test2;
        }a, b;
        a.test1 = 15;
        a.test2 = 17;
        b.test1 = 16;
        b.test1 = 18;
        a ^= b;
        b ^= a;
        a ^= b;
        cout << a.test1 << "\n";
        cout << b.test1 << "\n";
        cout << a.test2 << "\n";
        cout << b.test2 << "\n";
        return 0;
    }
    However I made it in like 30 seconds so something may be wrong with it.
    It gives three errors,
    "error C2676: binary '^=' : 'struct main::Test' does not define this operator or a conversion to a type acceptable to the predefined operator"
    you cant use the arithmatical operaters on structres or something like this a+b where a and b is a variable of type structures. but one thing u can do is overload the ^= this operator.

  6. #6
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    >but it could also be done using any data type
    How sure are you?

    You might want to read Hk_mp5kpdw's post one more time.

  7. #7
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,452
    > I thought some of you might find this trick useful.
    Actually, it's useless.
    is tha good method?

    The obvious way
    - is easier to explain
    - works on any type for which = is defined
    - is likely to produce quicker code.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  8. #8
    Registered User
    Join Date
    Jan 2005
    Posts
    181
    Code:
    originally posted  by swoopy
    >but it could also be done using any data type
    How sure are you?
    
    You might want to read Hk_mp5kpdw's post one more time.
    i cant able to understand. do u think that this logic works for structres. it could work for structure data members.

  9. #9
    Super Moderator VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,590
    I have bigger fish to fry than worrying about swapping values between variables.

    And there is a better way to do this with integers than using XOR. You can do SHR or SHL in assembly which rotates bits. But again it's all pointless.

  10. #10
    Registered User
    Join Date
    Mar 2004
    Posts
    536
    Quote Originally Posted by Chronom1
    Hey guys,
    I thought some of you might find this trick useful.
    Thank God for Boolean Logic :-D

    Note: This was done using integers but it could also be done using any data type including characters and structs because this command does not really care. All it cares about is the binary data.
    Of course, others have pointed out that it can't be done with "any data type" --- no need to go to structs or classes; try it with floats or doubles.

    Now as to "Thanking God", Many mathematicians subscribe to the dictum of 19th century German mathematician Leopold Kronecker
    "God gave us the integers; the rest is the work of Man,"
    Now, even if you don't go all of the way with this, you still have to give some credit to British mathematician George Boole whose publications in the 1850s reported his invention of a new form of mathematics in which logical expressions are represented in mathematical form. (Why do you think we call it Boolean Algebra?)

    This rather esoteric topic remained largely unknown to the general public until, in 1938, American mathematician Claude Shannon published his MIT master's thesis, in which he showed that Boole's expression values "TRUE" and "FALSE" could be applied to represent the states of switches in electronic circuits.

    The rest, as they say, is history.

    Now the little trick that you posted has been used to illustrate the concepts and actions of the exclusive-or functions on bits of binary numbers, and may, in fact serve some useful purpose in assembly language programs, but as a practical programming device in a language like C --- well, I don't think so.

    (Just my opinion, of course; everyone has an opinion, and everyone has a right to their opinion, and everyone has a right to disagree with anyone else's opinion.)

    Regards,

    Dave
    Last edited by Dave Evans; 02-23-2005 at 11:47 AM.

  11. #11
    Anti-Poster
    Join Date
    Feb 2002
    Posts
    1,399
    Quote Originally Posted by Chronom1
    However, there is a way to do this in which a third variable is not needed.
    Code:
    int a=5;
    int b=3;
    a ^= b;
    b ^= a;
    a ^= b;
    Don't try to write this up as a swap function, though. It doesn't even work with ints perfectly. Consider this:
    Code:
    void swap(int &a, int &b)
    {
        a ^= b;
        b ^= a;
        a ^= b;
    }
    
    int main()
    {
        int a = 5;
        int *b = &a;
        swap(a,*b);
        std::cout << a << " " << *b << std::endl; //outputs 0 0
        return 0;
    }
    It's a lot simpler to use the swap algorithm.
    Code:
    int main()
    {
        int a = 5;
        int *b = &a;
        std::swap(a,*b);
        std::cout << a << " " << *b << std::endl;
        return 0;
    }
    If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Unkown Hang
    By Bladactania in forum C Programming
    Replies: 31
    Last Post: 04-22-2009, 09:33 AM
  2. Replies: 15
    Last Post: 09-30-2008, 02:12 AM
  3. send and receive byte does not match
    By saipkjai in forum Networking/Device Communication
    Replies: 1
    Last Post: 02-09-2008, 12:09 AM
  4. Newbie sockets question/problem
    By (Slith++) in forum Networking/Device Communication
    Replies: 6
    Last Post: 12-05-2007, 11:23 PM
  5. assign values to charechter variables
    By simhap in forum C++ Programming
    Replies: 5
    Last Post: 10-07-2001, 07:55 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21