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!
Related
I understand standard usage of ternary operator..
string message = hasError=="Y" ? "There's an error!" : "Everything seems fine...";
But how do I add an OR in the subexpression..
if((hasError=="Y")||(seemsfine=="N")){
message="There's an error!";
}else{message="Everything seems fine...";
}
Any help is sincerely appreciated
Thanks
You can do it like this
string message = hasError == "Y" || seemsfine == "N" ? "There's an error!" : "Everything seems fine...";
There is not much difference. This is because the ternary operator in C# is that handy!
Ultimately, it is the result of the whole expression (that is, hasError == "Y" || seemsfine == "N") that matters, not how many conditions you have. You can put all other conditions if you want too, as long as the whole expression return true then it will assign the first element (left of :) to the variable and when the whole expression is false it assigns the second element (right of :) to the variable
Ternary operator is completely equivalent with if-else statement whose block is simply to assign value to single variable.
Thus,
if (a1 == 0 || a2 > 5 || a3 <= -7)
b = 1;
else
b = 2;
is completely equivalent to
b = a1 == 0 || a2 > 5 || a3 <= -7 ? 1 : 2; //note that there is no bracket here, but it is equivalent to if-else statement with bracket
When you have more than single variable to be assigned, then the equivalent breaks.
if (a1 >= 0)
b = 2;
else
c = 3; //notice the variable difference, you cannot use ternary operator anymore.
As long as it does not hinder the readability of the code for you, you can even put multiple ternary operators like this
b = a1 > 0 && a2 < 0 ? 1 : (a3 < 5 ? 2 : 3);
which is equivalent to
if (a1 > 0 && a2 < 0)
b = 1;
else if (a3 < 5)
b = 2;
else
b = 3;
The initial expression can be as simple or as complicated as you need it to be, as long as the condition ultimately evaluates to a single boolean value, just like the first line of your if statement.
In other words, this:
if ((hasError == "Y") || (seemsfine == "N"))
message="There's an error!";
else
message="Everything seems fine...";
Is equivalent to this:
string message = (hasError == "Y" || seemsfine == "N")
? "There's an error!"
: "Everything seems fine...";
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
How can I merge first n bits of a byte with last 8-n bits of another byte?
I know something like below for picking 3 bits from first and 5 from second (Which I have observed in DES encryption algorithm)
zByte=(xByte & 0xE0) | (yByte & 0x1F); But I don't know maths behind why we need to use 0XE0 and 0X1F in this case. So I am trying to understand the details with regards to each bit.
In C#, that would be something like:
int mask = ~((-1) << n);
var result = (x & ~mask) | (y & mask);
i.e. we build a mask that is (for n = 5) : 000....0011111, then we combine (&) one operand with that mask, the other operand with the inverse (~) of the mask, and compose them (|).
You could also probably do something more quickly just using shift operations (avoiding a mask completely) - but only if the data can be treated as unsigned (so Java might struggle here).
It just sounds like you don't understand how boolean arithmetic works? If this is your question it works like this:
0xEO and 0x1F are hexidecimal representations of numbers. If we convert these numbers to binary they would be:
0xE0 = 11100000
0x1F = 00011111
Additionally & (and) and | (or) are bitwise logical operators. To understand logical operators, first remember the 1 = true and 0 = false.
The truth table for & is:
0 & 0 = 0
0 & 1 = 0
1 & 0 = 0
1 & 1 = 1
The truth table for | is:
0 | 0 = 0
0 | 1 = 1
1 | 0 = 1
1 | 1 = 1
So let's breakdown your equation piece by piece. First we will evaluate the code in parenthesis first. We will walk through each number in binary and for the & operator if each operand has a 1 in the same bit position we will return 1. If either number has a 0 then we will return 0. After we finish the evaluation of the operands in the parenthesis we will then take the 2 resulting numbers and apply the | operator bit by bit. If either number has a 1 in the same bit position we will return 1. If both numbers have a 0 in the same bit position we will return 0.
For the sake of discussion, let's say that
xByte = 255 or (FF in hex and 11111111 in binary)
yByte = 0 or (00 in hex and 00000000 in binary)
When you apply the & and | operators we are going to compare each bit one at a time:
zByte = (xByte & 0xEO) | (yByte & 0x1F)
becomes:
zByte = (11111111 & 11100000) | (00000000 & 00011111)
zByte = 111000000 | 00000000
zByte = 11100000
If you understand this and how boolean logic works then you can use Marc Gravell's answer.
The math behind those numbers (0xE0 and 0x1F) is quite simple. First we are exploiting the fact that 0 & <bit> always equals 0 and 1 & <bit> always equals <bit>.
0x1F is 00011111 binary, which means that the first 3 bits will always be 0 after an & operation with another byte - and the last 5 bits will be the same they were in the other byte. Remember that every 1 in a binary number represents a power of 2, so if you want to find the mask mathematically it would be the sum of 2^x from x = 0 to n-1. Then you can find the opposite mask (the one that is 11100000) to extract the first 3 bit, you simply need to subtract the mask from 11111111, and you will get 11100000 (0xE0).
In java,
By using the following function we can get the first n bits of the first Byte and last 8 n bits of the second byte.
public class BitExample {
public static void main(String[] args) {
Byte a = 15;
Byte b = 16;
String mergedValue=merge(4, a, b);
System.out.println(mergedValue);
}
public static String merge(int n, Byte a, Byte b) {
String mergedString = "";
String sa = Integer.toBinaryString(a);
String sb = Integer.toBinaryString(b);
if(n>sa.length()) {
for(int i=0; i<(n-sa.length()); i++) {
mergedString+="0";
}
mergedString+=sa;
}else{
mergedString+=sa.substring(0, n);
}
if(8*n>sb.length()) {
for(int i=0; i<(8*n-sb.length()); i++) {
mergedString+="0";
}
mergedString+=sb;
}
return mergedString;
}
}
I saw a couple of questions here about the diference between && and & operators in C#, but I am still confused how it is used, and what outcome results in different situations. For example I just glimpsed the following code in a project
bMyBoolean = Convert.ToBoolean(nMyInt & 1);
bMyBoolean = Convert.ToBoolean(nMyInt & 2);
When it will result 0 and when >0? What is the logic behind this operator? What are the diferences between the operator '|'?
bMyBoolean = Convert.ToBoolean(nMyInt | 1);
bMyBoolean = Convert.ToBoolean(nMyInt | 2);
Can we use the &&, || operators and get the same results (possibly with different code)?
The && is a conditional and used in if statements and while
if(x>1 && y<3)
this means that x should be greater than 1 and y less than 3, satisfy both conditions
if(x>1 || y<3)
satisfy one of them
However, & and | are bitwise AND and OR respectively.
ex:
1 | 0 => 1
1 & 0 => 0
1 & 1 => 1
if this apply for straight integers, their corresponding binary value will be calculated and applied
2&1
=> 10 // the binary value of 2
&
01 // the binary value of 1
--
00 // the result is zero
The ampersand does bitwise AND on the integers in their binary representations.
The pipe does bitwise OR.
See here what those bitwise operations mean: http://en.wikipedia.org/wiki/Bitwise_operation
& and | is bit operations. You must use it on bit masks. && and || is logical operations so you can use it for only bool values.
Example of bit operation:
var a = 1;
var b = 2;
var c = a|b;
in binary format this means a = 00000001, b = 00000010
c = 00000011
So if you use bitmask c it will pass values 1, 2 or 3.
One more difference is that & operator computes the logical bitwise AND of its operands, if operands are not bool (integer in your case)
& operator is BItwise AND operator,it does manipulation on bits.
e.g. 5 & 3
0101 //5
0011 //3
----------
5&3= 0001 //1
| operator is BItwise OR operator,it does manipulation on bits.
5|3
0101 //5
0011 //3
----------
5|3= 0111 //7
&& operator is logical AND operator- it returns true if all conditions are true
e.g.
if((3>5)&&(3>4)) //returns true
if((6>5)&&(3>4)) //returns false
|| operator is logical OR operator- it returns true if one of the conditions is true
e.g.
if((3>5)||(3>4)) //returns true
if((6>5)||(3>4)) //returns true
if((6>5)||(5>4)) //returns false
Other answers explains for you the different between && and &, so assume you understand this. In here, I just try to explain your specified case.
First case
bMyBoolean = Convert.ToBoolean(nMyInt & 1);
bMyBoolean false when nMyInt = 0 because:
00
& 01
= 00;
Second case:
bMyBoolean = Convert.ToBoolean(nMyInt & 2);
bMyBoolean false when nMyInt = 0 or 1 because
00
& 10
= 00;
Or:
01
& 10
= 00;
The third and fourth cases with bitwise | are trivial because bMyBoolean always true with any nMyInt
bMyBoolean = Convert.ToBoolean(nMyInt | 1);
bMyBoolean = Convert.ToBoolean(nMyInt | 2);
You cannot apply && or || in this case because they are constraint only for bool, you will compiled errors.
Here is something interesting for & . bit-wise as & be, it can be used
to bool as in example below.
bool result = true;
result &= false;
Console.WriteLine("result = true & false => {0}", result );
//result = true & false => False
result = false;
result &= false;
Console.WriteLine("result = false & false => {0}", result );
//result = false & false => False
result = true;
result &= true;
Console.WriteLine("result = true & true => {0}", result );
//result = true & true => True
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.