Feedback

C# - Integer Rotate Left/Right

Veröffentlicht von am 12/23/2007
(1 Bewertungen)
Einfache Umsetzung eines Bit-Rotate für Integer-Werte.

Kann leicht für andere Datentypen (long, byte) umgeschrieben werden.
public static class Utils
{
	/// <summary>
	/// Rotates the given int value right 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 right side by the given distance</returns>
	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;
	}
}

2 Kommentare zum Snippet

v.wochnik schrieb am 12/24/2007:
Coole sache, aber was soll man denn damit machen?
Alexander Schuc schrieb am 12/24/2007:
Vielleicht brauchts mal ein Algorithmus denn du implementieren musst. :)
 

Logge dich ein, um hier zu kommentieren!