4

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# ?

johnchen902
  • 9,531
  • 1
  • 27
  • 69

2 Answers2

4

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;
    }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • What's also fun (imo) is that you can skip the 32's, like `(uvalue << shift) | (uvalue >> -shift)`, because that 32 only affects the bits that are ignored anyway. – harold Aug 30 '13 at 14:03
  • @harold: Yes, I considered that - but felt the 32 part was clearer. – Jon Skeet Aug 30 '13 at 14:04
  • @JonSkeet hah thanks ! 599k of reputation ! can u please just give me quick comment on substring in java the index can be higher then lenght but in c# how can i do that? –  Aug 30 '13 at 14:48
  • @studentofmp: That's an unrelated question - and I don't believe it's true anyway (it'll throw an exception). Ask a new question once you've validated your main point. – Jon Skeet Aug 30 '13 at 15:03
  • @JonSkeet i have done it and here my question http://stackoverflow.com/questions/18536161/whatis-similar-to-substring-of-java-if-index-is-higher-then-string-in-c –  Aug 30 '13 at 15:09
0

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));
}
Community
  • 1
  • 1
pinckerman
  • 4,115
  • 6
  • 33
  • 42