Problem with Bitwise Barrel Shift Rotate left and right in C#
In C++ I have code like this.
static UInt32 rol(UInt32 value, UInt32 bits)
{
bits &= 31;
return ((value << bits) | (value >> (32 - bits)));
}
static UInt32 ror(UInt32 value, UInt32 bits)
{
bits &= 31;
return ((value >> bits) | (value << (32 - bits)));
}
how would it look in C#? I think the same exa开发者_StackOverflowct way.. only problem
Error 2 Operator '>>' cannot be applied to operands of type 'uint' and 'uint'
Error 3 Operator '>>' cannot be applied to operands of type 'uint' and 'uint' Error 1 Operator '<<' cannot be applied to operands of type 'uint' and 'uint' Error 4 Operator '<<' cannot be applied to operands of type 'uint' and 'uint'
You should use int
type for the right side variable in shift operators.
You will have to cast the right side of the bitshift operator to int. If you cast like (int)(32 - bits)
, it should not affect your intended purpose. The right side is just expecting an int, probably because it's simpler that way and highly unlikely you'll ever want to shift more than 2 billion bits.
The right operand must be always type int.
int x << int bits
uint x << int bits
long x << int bits
ulong x << int bits
Add some parentheses and it works:
byte[] bytes = { 1, 2, 4, 8 };
UInt32 crc32 = ((UInt32)msg.Data[3] << 24) +
((UInt32)msg.Data[2] << 16) +
((UInt32)msg.Data[1] << 8) +
msg.Data[0];
精彩评论