0

I know there is similar questions to my question, however, they aren't the same. All of them are just normal shifts, circular shifts etc. not having a through Carry flag.

I am trying to implement a method that does a right rotate through carry flag, carry flag being 1, current code:

public static int RotateRight(int value, int count = 2)
{
   uint val = (uint)value;
   return (int)((val >> count) | (val << (32 - count)));
}

However, this works only as normal shift, an input of 16 returns 4. How would one create a carry flag?

Before an admin points to this question C# bitwise rotate left and rotate right this does a normal rotate without a through carry flag.

Rotate through carry

Another example of this:

10 >> 2 with carry through flag of 1

1   00010000    
Rotate with carry   >>  2   
0   10001000    
0   01000100
UnkG
  • 1
  • 1
  • 1
    `carry flag being 1` - what do you mean by this? - going in, coming out? Where is this value being held in your code sample? – 500 - Internal Server Error Oct 05 '22 at 14:38
  • @500-InternalServerError well that is the issue, I am not sure how to reimplement this flag with a bitwise operation. As x >> 2 does the bitshift in code I am note sure I can modify it to add the 1 at the start. I tried using a hacky method. Convert decimal to string with already shifted values, add 1 at index 1 ( shifted by 2), however this is kind of a hacky way of doing it and doesn't cover all cases – UnkG Oct 05 '22 at 14:51

1 Answers1

0

If I'm understanding you correctly, here my really straigth-forward, off the top of my head, totally unoptimized way of doing it:

int RotateRightThroughCarry(uint value, int count, ref uint carry)
{
  // width assumed to be 32 bits
  // carry assumed to be either 0 or 1    
  for(int i = 0; i < count; i++)
    value = RotateRightOneBitThroughCarry(value, ref carry);
  return value;
}

int RotateRightOneBitThroughCarry(uint value, ref uint carry)
{
  int newCarry = value & 1;
  int newValue = (value >> 1) | (carry << 31);
  carry = newCarry;
  return newValue;
}