What in the world does a ^= operator do? - c#

I am looking at a permutation code and trying to understand how it does what it does, but one operation has me at a loss: ^=. Google will not let me search these characters, so can anyone tell me what it's doing, what does this operator mean? You can see an example of it below. Thank you!
private void swap(ref char a, ref char b)
{
if (a == b)
return;
a ^= b;
b ^= a;
a ^= b;
}

From MSDN:
An expression of the form
x ^= y
is evaluated as
x = x ^ y
except that x is only evaluated once. So, if your x is a property, it will be called once to get and once to set the value.
The ^ (XOR) operator performs a bitwise exclusive-OR operation on integral operands and logical exclusive-OR on bool operands (sum on modulus 2):
false ^ false = false;
false ^ true = true;
true ^ false = true;
true ^ true = false;
XOR operator is quite useful in cryptography as the main it's property is that
a ^ b ^ a == b;
So your code is simply add the values for a two variables so they are swaped.

a ^= b stores in a the value of a^b, which is the exclusive-or of a and b.

It's the exclusive-OR assignment operator.
You can learn more here:https://msdn.microsoft.com/en-us/library/0zbsw2z6.aspx

The exclusive-OR assignment operator.
https://msdn.microsoft.com/en-us/library/0zbsw2z6.aspx

Related

Python to C# explanation

I have been converting a Python script to C#, I am 99% there but I am having trouble understanding the following piece of code
# The lower 8-bits from the Xorshift PNR are subtracted from byte
# values during extraction, and added to byte values on insertion.
# When calling deobfuscate_string() the whole string is processed.
def deobfuscate_string(pnr, obfuscated, operation=int.__sub__):
return ''.join([chr((ord(c) operation pnr.next()) & 0xff) for c in obfuscated])
Could you please explain the code above? what does operation pnr.next() do? If you could help maybe convert this method to C# that would be even better but an explanation of the above would be great.
Full source can be found at
https://raw.githubusercontent.com/sladen/pat/master/gar.py
The snippet you provided is not a valid Python code. One cannot write a function name in the place of an infix operator. I think it is meant to be like this:
# The lower 8-bits from the Xorshift PNR are subtracted from byte
# values during extraction, and added to byte values on insertion.
# When calling deobfuscate_string() the whole string is processed.
def deobfuscate_string(pnr, obfuscated, operation=int.__sub__):
return ''.join([chr(operation(ord(c), pnr.next()) & 0xff) for c in obfuscated])
You see, this way it will execute the the operation on ord(c) and pnr.next(). This way the translation to C# is straightforward, operation should be of type Func<int, int, int>.
This might give you an idea:
public static T Next<T>(IEnumerator<T> en) {
en.MoveNext();
return en.Current;
}
public static string deobfuscate_string(IEnumerator<int> pnr, string obfuscated, Func<int, int, int> operation = null) {
if (operation == null) operation = (a, b) => a - b;
return string.Join("", from c in obfuscated select (char)operation((int)c, Next(pnr)));
}
EDIT: added default parameter to deobfuscate_string
The function deobfuscate_string takes an iterable pnr, a string obfuscated and an operation that is by default substract.
For each character c in the string obfuscated
It apply the
operator (substract by default) to the value of the character with
the next element in pnr.
Then it uses & 0xff to ensure result is in range 255
Every thing is then combine in a string.
So, it just encrypt the input by rotating every characters from a known set of rotations.
Notice: The code is not valid as operation cannot by used this way, I just explain the goal here.
Thank you everyone for posting responses, I ended up grabbing a Python debugger and working it through.
private static byte[] deobfuscate_string(XORShift128 pnr, byte[] obfuscated)
{
byte[] deobfuscated = new byte[obfuscated.Length];
for (int i = 0; i < obfuscated.Length; i++)
{
byte b = Convert.ToByte((obfuscated[i] - pnr.next()) & 0xff);
deobfuscated[i] = b;
}
Array.Reverse(deobfuscated);
return deobfuscated;
}
private class XORShift128
{
private UInt32 x = 123456789;
private UInt32 y = 362436069;
private UInt32 z = 521288629;
private UInt32 w = 88675123;
public XORShift128(UInt32 x, UInt32 y)
{
this.x = x;
this.y = y;
}
public UInt32 next()
{
UInt32 t = (x ^ (x << 11)) & 0xffffffff;
x = y;
y = z;
z = w;
w = (w ^ (w >> 19) ^ (t ^ (t >> 8)));
return w;
}
}
Above is that I ended up with

Swap two numbers without using another variable [duplicate]

This question already has answers here:
Swap two variables without using a temporary variable
(29 answers)
Closed 8 years ago.
Swap two variables without using a temp variable
if
int a=4;
int b=3;
I need to swap these variable and get output as
a=3 and b=4
without using another variable in C#
Use Interlocked.Exchange()
int a = 4;
int b = 3;
b = Interlocked.Exchange(ref a, b);
Tell me more
From MSDN:
Sets a 32-bit signed integer to a specified value as an atomic operation, and then returns the original value
EDIT: Regarding Esoteric's fine link above (thank-you), there's even a Interlocked.Exchange() for double that may help there too.
use the following concept
int a=4 ;
int b=3 ;
a=a+b ; // a=7
b=a-b ; // b=7-3=4
a=a-b ; // c=7-4=3
There are actually a couple of ways.
The following is considered an obfuscated swap.
a ^= b;
b ^= a;
a ^= b;
a = a + b;
b = a - b;
a = a - b;
Works the same with any language.
Using addition and subtraction
a = a + b;
b = a - b;
a = a - b;
Using xor operator
a = a ^ b;
b = a ^ b;
a = a ^ b;
http://chris-taylor.github.io/blog/2013/02/25/xor-trick/

Negate a boolean based on another boolean

What's the short, elegant, bitwise way to write the last line of this C# code without writing b twice:
bool getAsIs = ....
bool b = ....
getAsIs ? b : !b
The truth table can be expressed as:
getAsIs b getAsIs ? b : !b
--------------------------------
0 0 1
0 1 0
1 0 0
1 1 1
The result can be expressed as:
result = (getAsIs == b);
Try using binary XOR (^ Operator (C# Reference)):
bool getAsIs = true;
bool b = false;
bool result = !(getAsIs ^ b);
I think it's
var foo = !(getAsIs ^ b)
Short, elegant, but definitely a head-scratcher!

C# compound assignment operator ^=

What does this operator ^= mean in c#?
It means bitwise XOR the value of the LHS expression with the value of the RHS expression, and assign it back to the LHS expression.
So for example:
int x = 10;
int y = 3;
x ^= y; // x = 10 ^ 3, i.e. 9
The LHS expression is only evaluated once, so if you have:
array[GetIndex()] ^= 10;
that would only call GetIndex once. But please don't do that, 'cos it's nasty :)
See also the relevant MSDN page.
You may also find Eric Lippert's recent April Fool's Day blog post on compound assignment operators amusing - and part one of the series, which was rather more serious, may prove enlightening.
this:
x ^= y;
is equivalent to this:
x = x ^ y;
In words, set x to the value of x exclusive or'ed with y.
The exclusive-OR assignment operator.
An expression of the form
x ^= y
is evaluated as
x = x ^ y
except that x is only evaluated once. The ^ operator performs a bitwise exclusive-OR operation on integral operands and logical exclusive-OR on bool operands.
http://msdn.microsoft.com/en-us/library/0zbsw2z6.aspx
This is the "exclusive or assignment" operator. Details are at http://msdn.microsoft.com/en-us/library/0zbsw2z6(v=VS.100).aspx
XOR. a ^= b is the same as a = a ^ b, where a and b are integer types of some sort.

When to use "^" operator

What is the operator below ^?
When to use it?
My programing language is C#.
^ is a Logical XOR Operator if the operands are bools, otherwise it's a Bitwise XOR Operator
Binary ^ operators are predefined for the integral types and bool. For integral types, ^ computes the bitwise exclusive-OR of its operands. For bool operands, ^ computes the logical exclusive-or of its operands; that is, the result is true if and only if exactly one of its operands is true.http://msdn.microsoft.com/en-us/library/zkacc7k1.aspx
It's the XOR operator. It's used in bitwise operations, where the result is true if the left side is true or the right side is true, but false if both are true or both are false. So 0xf8 ^ 0x3f would be:
1111 1000
0011 1111
---------
1100 0111
Which is C7 in hexadecimal.
In general, if you're not doing bitwise arithmetic, you won't need to worry about it.
http://msdn.microsoft.com/en-us/library/zkacc7k1(VS.71).aspx
It is often used as a way to "flip
bits" by XORing it with 1 (to flip),
0 (to keep). Usually this is useful
in encryption/decryption/hashing. ** THIS IS ACTUALLY USEFUL **
Example:
101 ^
110
-----
011 //Flip the first 2, keep the 3rd
It can also be used for a swapping
method (though, using the standard
way and generics is probably more ideal):
Example:
int myMoney = 10;
int yourMoney = 50;
Swap(myMoney, yourMoney)
public void Swap(ref int a, ref int b) //No 'temp' variable necessary
{
a ^= b;
b ^= a;
a ^= b;
}
It is used in binary arithmetic. ** THIS IS ACTUALLY USEFUL **
Flip a bool (though, I'd rather use bool x = true; x != x;
Example:
public bool flip(ref bool b)
{
b ^= true;
}
I think of it as a binary operator just like ||, &&, etc...
If I were writing logic and ended up with:
if( (condition1 && !condition2) || (condition2 && !condition1) )
{
}
I might rewrite it as:
if( condition1 ^ condition2)
{
}
That said, I'd take it on a case by base basis and weigh the benefit of brevity vs. potential obfuscation due to relative obscurity.
Its Exclusive OR (XOR) operator as mentioned by others. Here is the truth table for XOR
P Q P^Q
T T F
T F T
F T T
F F F
Note that P^Q is equal to P!=Q. Sometimes P!=Q is used in the code instead of XOR operator.

Categories

Resources