Rotate Left/Right

Tja.. jetzt ist es mir passiert. Shiften reicht mir nicht, ich brauche ein Rotate! In der .net Klassenbibliothek hab ichs nicht gefunden. Also mal fix selber überlegt und umgesetzt.

[code=c#;Integer Rotate Left/Right]
public static class Utils
{
///

/// Rotates the given int value right by the specified number of bits.
///

/// The integer to rotate
/// The number of bits to rotate
/// Returns the given int rotated right side by the given distance
public static int RotateRight(int i, int distance)
{
uint num = (uint)i;
int length = (sizeof(int) * 8);
distance = distance % length;
uint add = num << (length – distance);
num = num >> distance;
num = num | add;
return (int)num;
}

/// <summary>
/// Rotates the given int value left by the specified number of bits.
/// </summary>
/// <param name="number">The integer to rotate</param>
/// <param name="distance">The number of bits to rotate</param>
/// <returns>Returns the given int rotated left side by the given distance</returns>
public static int RotateLeft(int i, int distance)
{
    uint num = (uint)i;
    int length = (sizeof(int) * 8);
    distance = distance % length;
    uint add = num >> (length - distance);
    num = num << distance;
    num = num | add;
    return (int)num;
}

}
[/code]

Das ganze ist auch auf dotnet-snippets.de zu bewundern, und zu bewerten. 🙂

One thought on “Rotate Left/Right

  1. Hallo!

    Auf dotnet-snippets.de schreibst Du, daß es einfach wäre die Methode auf u.a. long umzuschreiben. Leider gelingt es mir nicht. Bekomme bei
    [quote]ulong add = num >> (length – distance);[/quote]
    (4. Zeile der Methode) die Fehlermeldung:
    [quote]Fehler 1 Der Operator ">>" kann nicht auf Operanden vom Typ "ulong" und "long" angewendet werden.[/quote]
    Kannst Du mir vielleicht zeigen wie ich es umschreibe.

Kommentare sind nicht möglich.