0

I got a question regarding shifting bits within an unsigned integer. I've got two unsigned integers, let's say var1 and var2. I need to take the left most var1 bits of var2 and move them to the right most position. So if var1 is 12 and var2 is 0x13ac8d08 that would result in var2 becoming 0xc8d0813a. Can anyone help me how to do that in C#?

thanks

Michael

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
bicycle
  • 8,315
  • 9
  • 52
  • 72

2 Answers2

2

Try this:

var2 = (var2 << var1) | (var2 >> (32 - var1));

In method form:

uint CyclicShiftLeft(uint input,int countBits)
{
   return (input << countBits) | (input >> (32 - countBits))
}

Edit

Please see the comments for the significance of the 32 in the above code.

logicnp
  • 5,796
  • 1
  • 28
  • 32
  • 1
    Much more elegant than what I started to do. Just keep in mind that 32 may change to 64 or 16, depending on your unsigned number (if it's a unsigned long, it should be 64) – zmbq Sep 11 '12 at 05:49
  • An explanation here for the newbie OP would be great. I started a long-winded answer, but yours was too quick, and right on the money. – Jonathon Reinhart Sep 11 '12 at 05:50
  • @zmbq to be quite clear, you could always use `sizeof(uint)*8` or whatever type you're using. I tried to whip up a generic extension method, but unfortunately [C# doesn't have generic constraints on integral types](http://stackoverflow.com/questions/32664/c-sharp-generic-constraint-for-only-integers). – Jonathon Reinhart Sep 11 '12 at 06:00
  • @logicnp Thanks guys, return (input << countBits) | (input >> (32 - countBits)) works perfect! – bicycle Sep 11 '12 at 06:26
0

First of all, I don't understand the function of var1 in your question. I also, you don't specify the number of bits to shift, or more correctly rotate. From the example I assume that you want to move the 12 most significant bits to the least significant position. (Is that what var1 is for?)

 unsigned int var2 = 0x13ac8d08;
 unsigned int temp = (var2 >> 20) & 0xfff; // store and mask 12 bits in least significant position 
  var2 <<= 12; // shift left
  var2 &= 0xfffff00; // mask to make sure no bits dragged from lsb by shift
  var2 |= temp;

The masking may not be strictly necessary, but it never hurts to be sure. Shift commands in machine language may sometimes extend the most or least significant bit, and you don't want that.

Aharon Manne
  • 712
  • 3
  • 11
  • 34