PROBLEM
write a code to reverse a C-Style String - ( C-String means that “abcd” is represented as five characters, including the null character )

EXCLUSIVE DISJUNCTION or EXCLUSIVE OR is a logical operation that outputs TRUE whenever both inputs differ (one is true, the other is false)

The XOR swap is an algorithm that uses the XOR bitwise operation to swap values of distinct variables having the same data type without using a temporary variable.
"Distinct" means that the variables are stored at different memory addresses; the actual values of the variables do not have to be different.

Conventional swapping requires the use of a temporary storage variable.
Using the XOR swap algorithm, however, no temporary storage is needed. The algorithm is as follows :

STEP 1 : X := X XOR Y
STEP 2 : Y := X XOR Y
STEP 3 : X := X XOR Y

EXAMPLE : decimal 5 = 0101 and 3 = 0011
swap x = 5 - and y = 3
STEP 1 : x = x XOR y ----> 0101 XOR 0011 = 0110 -> x
STEP 2 : y = x XOR y ----> 0110 XOR 0011 = 0101 -> y => is now 0101 = 5 (decimal)
STEP 3 : x = x XOR y ----> 0101 XOR 0011 = 0110 -> x => is now 0110 = 3 (decimal)

the values are switched x = 3 and y = 5

``````<blockquote><code>sortingXOR.h
#ifndef SORTINGXOR_H_
#define SORTINGXOR_H_
class sortingXOR {
public:
sortingXOR();

// swap method using XOR algorithm
void swap(char&amp;, char&amp;);

// first reverse method
void reverse_method1(char* );

// second reverse metod
void reverse_method2(char *);

virtual ~sortingXOR();
};

#endif /* SORTINGXOR_H_ */
</code></blockquote>
<blockquote><code>
sortingXOR.cpp
#include <iostream>
#include <cstring>
#include "sortingXOR.h"

using namespace std;

sortingXOR::sortingXOR(){ }

STEP 1 : X := X XOR Y
STEP 2 : Y := X XOR Y
STEP 3 : X := X XOR Y

void sortingXOR::swap(char &a, char &b)
{
a = a^b; // STEP 1 : a = a XOR b
b = a^b; // STEP 2 : b = a XOR b
a = a^b; // STEP 3 : a = a XOR b
}

void sortingXOR::reverse_method1(char *s)
{
int n = strlen(s);
for(int i=0; i < n / 2; ++i)
swap(s[i], s[n-i-1]);
}

void sortingXOR::reverse_method2(char *s)
{
if(!s)
return;
char *p = s, *q = s;
while(*q) ++q;
--q;
while(p < q)
swap(*p++, *q--);
}

sortingXOR::~sortingXOR(){ }
</code></blockquote>

and the main program :

<blockquote><code>
main.cpp

#include <iostream>

// include the sorting SOR algorithm
#include "sortingXOR/sortingXOR.h"

using namespace std;

int main()
{
char s[] = "1234567890";

cout << " initial string " << s << endl;

sortingXOR mysort;
mysort.reverse_method1(s);

// display string
cout << s << endl;

sortingXOR *mysort_new = new sortingXOR();
mysort_new->reverse_method2(s);

// display string
cout << s << endl;

return 0;
}
</code></blockquote>``````

the git websource :
https://github.com/eandbsoftware/bestCPP.git