Flips the bytes of the specified number. - CSharp System

CSharp examples for System:Byte Array

Description

Flips the bytes of the specified number.

Demo Code


using System.Net;

public class Main{
        /// <summary>
        /// Flips the bytes of the specified number.
        /// </summary>
        /// <param name="number">The number to flip the bytes of.</param>
        public static void FlipBytes(ref short number)
        {//from   ww w  .  j a va2  s .c o m
            number = unchecked((short)FlipNumber(number, 2));
        }
        /// <summary>
        /// Flips the bytes of the specified number.
        /// </summary>
        /// <param name="number">The number to flip the bytes of.</param>
        public static void FlipBytes(ref ushort number)
        {
            number = unchecked((ushort)FlipNumber(number, 2));
        }
        /// <summary>
        /// Flips the bytes of the specified number.
        /// </summary>
        /// <param name="number">The number to flip the bytes of.</param>
        public static void FlipBytes(ref int number)
        {
            number = unchecked((int)FlipNumber(number, 4));
        }
        /// <summary>
        /// Flips the bytes of the specified number.
        /// </summary>
        /// <param name="number">The number to flip the bytes of.</param>
        public static void FlipBytes(ref uint number)
        {
            number = unchecked((uint)FlipNumber(number, 4));
        }
        /// <summary>
        /// Flips the bytes of the specified number.
        /// </summary>
        /// <param name="number">The number to flip the bytes of.</param>
        public static void FlipBytes(ref long number)
        {
            number = FlipNumber(number, 8);
        }
        /// <summary>
        /// Flips the bytes of the specified number.
        /// </summary>
        /// <param name="number">The number to flip the bytes of.</param>
        public static void FlipBytes(ref ulong number)
        {
            number = (ulong)FlipNumber((long)number, 8);
        }
        private static long FlipNumber(long number, int byteCount)
        {
            int i = 0;
            long oldNumber = number;
            long newNumber = 0;
            while (i++ < byteCount)
            {
                newNumber <<= 8;
                newNumber |= oldNumber & 0xFF;
                oldNumber >>= 8;
            }

            number = newNumber;
            return number;
        }
}

Related Tutorials