I saw a thread lately on this site to rotate an integer.
Seemed like a fun project to do.
There are probably more efficient solutions out there but this is mine, and indeed it was fun!
It is mostly a demo on how you could use the less known shift operators.
Rotate a byte in C#
using System;
namespace RotateByte
{
class Program
{
static void Main(string[] args)
{
byte value = 208;
Console.WriteLine("Rotation of a byte demo:");
Console.WriteLine("A value of {0} gives {1}.", value, RotateByte(value));
Console.ReadKey();
}
static byte RotateByte(byte B)
{
const int byteLength = 8;
uint value = (uint)B; // Shift operators do not work on a byte
uint mask = 1 << byteLength - 1; //set mask to highest bit = 128
uint extract = 0;
uint rotated = 0;
uint result = 0;
for (int i = 0; i < byteLength; i++)
{
extract = value & mask; // Extract one bit from byte
mask = mask >> 1; // Set mask to next lower bit
rotated = extract << 2 * i + 1; // Move bit up
result += rotated; // Add to result
rotated = 0; // Clear
}
result >>= byteLength; // Move all bits back ==> rotated!
return (byte)result;
}
}
}
kel634 0 Newbie Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.