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.

``````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;
}
}
}``````
2
Contributors
1
Reply
3
Views
8 Years
Discussion Span
Last Post by kel634

This is a simpler version:
- get the last bit of the number (0 or 1)
- << 1 the number
- & with 1111 1111 (only needed if lastbit is 1 but I did it anyway)
- add the last bit to this number

``````static int Rotate(int x)
{
const int bytelength = 8;
const int fullbyte = 255;   // 1111 1111
int mask = 1 << (bytelength - 1);   // mask = 1000 0000
int lastbit = (mask & x) >> (bytelength - 1);
return lastbit + ((x << 1) & fullbyte);
}
static void Main(string[] args)
{
int k = 128;
Console.WriteLine("original value: " + k);
Console.WriteLine("rotated value: " + Rotate(k));
Console.ReadLine();
}``````
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.