Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bit-shifting with Int64

An Int64 variable needs to be shifted. I am parsing pseudo mathematical functions from a database file. The Variables are uint32 or int32 so i did put them into an Int64 to handle them equally without loosing anything. In one of my treenodes i need to bitshift Int64.

Unfortunately the shift operator does not apply to Int64. Is there a standard way of bit shifting Int64 that i am not aware of?

//Int32 Example works
int a32 = 1;
int b32 = 2;
int c32 = a32 >> b32;

//Int64 Example does not compile
Int64 a64 = 1;
Int64 b64 = 2;
Int64 c64 = a64 >> b64; //invalid operator
like image 476
Johannes Avatar asked Jul 05 '12 11:07

Johannes


People also ask

Can you bit shift an integer?

Logical bit shifting may be useful for multiplying or dividing unsigned integers by powers of two. For example, if the value "0001" or "1" is shifted left, it becomes "0010" or "2," shifted to the left again it becomes "0100," or "4." Shifting to the right has an opposite effect of dividing the value by two per shift.

What is the purpose of bit shifting?

Bitshifting shifts the binary representation of each pixel to the left or to the right by a pre-defined number of positions. Shifting a binary number by one bit is equivalent to multiplying (when shifting to the left) or dividing (when shifting to the right) the number by 2.

What does bit shifting by 0 do?

1 in binary is 0001 , then bitshifting it by 0 won't do anything, which aligns with what you observed. So any number x << 0 is equivalent to x * 2^0 , which is x * 1 , which is just x .

Is bit shifting constant time?

On most modern CPU architectures, such as an i5 or i7, bitshifting isn't only constant time, it's typically done in just a couple clock cycles max. It's generally considered one of the fastest operations you can do.


1 Answers

I believe the right-hand operand of the right-shift operator (in C#) always takes an int, even if the left-hand operand is not an int.

Official details here in C# Specification on MSDN.

like image 193
reuben Avatar answered Sep 28 '22 08:09

reuben