Rotate a byte in C#

ddanbe 0 Tallied Votes 2K Views Share

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;
        }
    }
}
kel634 0 Newbie Poster

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();
        }
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.