What does << in C# mean and is there a SQL equivalent? - c#

Can someone explain what the << is doing in this function:
return (b & (1 << pos)) != 0;
And is there an equivalent to this in T-SQL?

It's bitwise shift.
Shift is not mentioned on Bitwise Operators (Transact-SQL) page so I would say they are not awailable in TSQL. However, bitwise shift in 2-based numeric system is equivalent to multiplying by 2, so you can use that to perform similar operation without actually using bitwise shift.

<< in C# means "shift number left". You can simulate it by multiplying by a corresponding power of two:
b & POWER(2, pos) <> 0

Related

How to use bitwise NOT operator with shift operator in C#?

I don't understand how this expression works.
~(1 << 1) = -3
What I do understand is that 1 << 1 has a value of 10 in binary and 2 in base 10. How did it get a -3 with the NOT operator? How does shift operators work with NOT operators?
The bitwise inverse operator is entirely separate from the shift here.
You've started with input of 10 (binary) - which has a full 32-bit representation of
00000000_00000000_00000000_00000010
The bitwise inverse is therefore:
11111111_11111111_11111111_11111101
... which is the binary representation of -3 (in 32-bit two's complement).

What is code for logical right shift in C#?

I am trying to translate Java code with logical right shift (>>>) (Difference between >>> and >>) to C#
Java code is
return hash >>> 24 ^ hash & 0xFFFFFF;
C# is marked >>> as syntax error.
How to fix that?
Update 1
People recommend to use >> in C#, but it didn't solve problem.
System.out.println("hash 1 !!! = " + (-986417464>>>24));
is 197
but
Console.WriteLine("hash 1 !!! = " + (-986417464 >> 24));
is -59
Thank you!
Java needed to introduce >>> because its only unsigned type is char, whose operations are done in integers.
C#, on the other hand, has unsigned types, which perform right shift without sign extension:
uint h = (uint)hash;
return h >> 24 ^ h & 0xFFFFFF;
For C# you can just use >>
If the left-hand operand is of type uint or ulong, the right-shift operator performs a logical shift: the high-order empty bit positions are always set to zero.
From the docs.

Convert Python array/byteshift/struct to C#

I'm struggling on converting an apparently easy code from Python to C# as below:
def computeIV(self, lba):
iv = ""
lba &= 0xffffffff
for _ in xrange(4):
if (lba & 1):
lba = 0x80000061 ^ (lba >> 1)
else:
lba = lba >> 1
iv += struct.pack("<L", lba)
return iv
I'm used to C# logic and I really can't understand arrays bitmask ...
You can make use of BitArray Class in C# which manages a compact array of bit values, which are represented as Booleans, where true indicates that the bit is on (1) and false indicates the bit is off (0).
It offers AND, OR, NOT, SET and XOR functions.
For Shift operation, a possible solution can be found here:
BitArray - Shift bits or Shifting a BitArray

Quick: Set top 2 bits of int

This is actually fairly tricky to Google.
How do you SET (bitwise or) the top two bits of a 32 bit int?
I am getting compiler warnings from everything I try.
Try this:
integerVariable |= 3 << 30;
It may be more clear to use (1 << 31) | (1 << 30) instead of (3 << 30), or you could add a comment about the behavior. In any case, the compiler should be able to optimize the expression to a single value, which is equal to int.MinValue >> 1 == int.MinValue / 2.
If it's a uint:
uintVar |= 3u << 30;
integerVariable |= 0xC0000000;
Use 0xC0000000u for an unsigned integer variable.
Showing the entire 32-bit integer in hex notation is clearer to me than the bit shifts in Mehrdad's answer. They probably compile to the same thing, though, so use whichever looks clearer to you.

When to use Shift operators << >> in C#?

I was studying shift operators in C#, trying to find out
when to use them in my code.
I found an answer but for Java, you could:
a) Make faster integer multiplication and division operations:
*4839534 * 4* can be done like this:
4839534 << 2
or
543894 / 2 can be done like this: 543894 >> 1
Shift operations much more faster than multiplication for most of processors.
b) Reassembling byte streams to int values
c) For accelerating operations with graphics since Red, Green and Blue colors coded by separate bytes.
d) Packing small numbers into one single long...
For b, c and d I can't imagine here a real sample.
Does anyone know if we can accomplish all these items in C#?
Is there more practical use for shift operators in C#?
There is no need to use them for optimisation purposes because the compiler will take care of this for you.
Only use them when shifting bits is the real intent of your code (as in the remaining examples in your question). The rest of the time just use multiply and divide so readers of your code can understand it at a glance.
Unless there is a very compelling reason, my opinion is that using clever tricks like that typically just make for more confusing code with little added value. The compiler writers are a smart bunch of developers and know a lot more of those tricks than the average programmer does. For example, dividing an integer by a power of 2 is faster with the shift operator than a division, but it probably isn't necessary since the compiler will do that for you. You can see this by looking at the assembly that both the Microsoft C/C++ compiler and gcc perform these optimizations.
I will share an interesting use I've stumbled across in the past. This example is shamelessly copied from a supplemental answer to the question, "What does the [Flags] Enum Attribute mean in C#?"
[Flags]
public enum MyEnum
{
None = 0,
First = 1 << 0,
Second = 1 << 1,
Third = 1 << 2,
Fourth = 1 << 3
}
This can be easier to expand upon than writing literal 1, 2, 4, 8, ... values, especially once you get past 17 flags.
The tradeoff is, if you need more than 31 flags (1 << 30), you also need to be careful to specify your enum as something with a higher upper bound than a signed integer (by declaring it as public enum MyEnum : ulong, for example, which will give you up to 64 flags). This is because...
1 << 29 == 536870912
1 << 30 == 1073741824
1 << 31 == -2147483648
1 << 32 == 1
1 << 33 == 2
By contrast, if you set an enum value directly to 2147483648, the compiler will throw an error.
As pointed out by ClickRick, even if your enum derives from ulong, your bit shift operation has to be performed against a ulong or your enum values will still be broken.
[Flags]
public enum MyEnum : ulong
{
None = 0,
First = 1 << 0,
Second = 1 << 1,
Third = 1 << 2,
Fourth = 1 << 3,
// Compiler error:
// Constant value '-2147483648' cannot be converted to a 'ulong'
// (Note this wouldn't be thrown if MyEnum derived from long)
ThirtySecond = 1 << 31,
// so what you would have to do instead is...
ThirtySecond = 1UL << 31,
ThirtyThird = 1UL << 32,
ThirtyFourth = 1UL << 33
}
Check out these Wikipedia articles about the binary number system and the arithmetic shift. I think they will answer your questions.
The shift operators are rarely encountered in business applications today. They will appear frequently in low-level code that interacts with hardware or manipulates packed data. They were more common back in the days of 64k memory segments.

Categories

Resources