Reputation:
in java there is a function called rotatetoleft that generate a nunmber generated
int n;
n = Integer.rotateLeft(1, 5);
System.out.print(n);
output; 32
what is similar to this in c# ?
Upvotes: 4
Views: 199
Reputation: 1503280
It sounds like you're just after the <<
operator, but that only performs a left-shift; it won't rotate into the LSB. To do that, you'd have to do a mixture of shifts and ORs. For example:
static int RotateLeft(int value, int shift)
{
return (value << shift) | (value >> (32 - shift));
}
Note that this won't quite work properly if value
has its top bit set due to sign extension on the shift right. You can fix that by doing the arithmetic in uint
:
static int RotateLeft(int value, int shift)
{
unchecked
{
uint uvalue = (uint) value;
uint uresult = (uvalue << shift) | (uvalue >> 32 - shift);
return (int) uresult;
}
}
Upvotes: 4
Reputation: 4213
I don't think there's something like that in C#, I've found a similar question here and an answer suggests this implementation: (C language)
unsigned int _rotl(const unsigned int value, int shift)
{
if ((shift &= sizeof(value) * 8 - 1) == 0)
return value;
return (value << shift) | (value >> (sizeof(value)*8 - shift));
}
unsigned int _rotr(const unsigned int value, int shift)
{
if ((shift &= sizeof(value) * 8 - 1) == 0)
return value;
return (value >> shift) | (value << (sizeof(value)*8 - shift));
}
Upvotes: 0