Encodes an integer into a 4-byte array, in big endian. - CSharp System

CSharp examples for System:Byte Array

Description

Encodes an integer into a 4-byte array, in big endian.

Demo Code


using System.Text;
using System.Security.Principal;
using System.IO;//from  www. j a  v a 2s.  c om
using System;

public class Main{
        /// <summary>
        /// Encodes an integer into a 4-byte array, in big endian.
        /// </summary>
        /// <param name="number">The integer to encode.</param>
        /// <returns>Array of bytes, in big endian order.</returns>
        public static byte[] GetBigEndianBytes(this uint number)
        {
            byte[] bytes = BitConverter.GetBytes(number);
            if (BitConverter.IsLittleEndian)
            {
                bytes.SwapBytes(0, 3);
                bytes.SwapBytes(1, 2);
            }
            return bytes;
        }
        public static void SwapBytes(this byte[] bytes, int index1, int index2)
        {
            byte temp = bytes[index1];
            bytes[index1] = bytes[index2];
            bytes[index2] = temp;
        }
}

Related Tutorials