Converts int32 to the array of bytes size 4 - CSharp System

CSharp examples for System:Byte Array

Description

Converts int32 to the array of bytes size 4

Demo Code

// Licensed under the Apache License, Version 2.0 (the "License"); 

public class Main{
        /// <summary>
        /// Converts int32 to the array of bytes size 4
        /// </summary>
        /// <param name="value">Int32 value</param>
        /// <returns>Array of bytes of size 4.</returns>
        public static byte[] Int32ToBytes(Int32 value)
        {//from  w ww .java 2s .c  om
            return Int32ToBytes(value, 4);
        }
        /// <summary>
        /// Creates array of bytes, then converts int32 to the array
        /// </summary>
        /// <param name="value">Int32 value</param>
        /// <param name="bytesNum">Number of bytes </param>
        /// <returns>Array of bytes of size bytesNum.</returns>
        public static byte[] Int32ToBytes(Int64 value, int bytesNum)
        {
            var bytes = new byte[bytesNum];
            for (int i = 0; i < bytesNum; ++i)
            {
                bytes[bytesNum - 1 - i] = (byte)((value & (0xFF << (i << 3))) >> (i * 8));
            }

            return bytes;
        }
        /// <summary>
        /// Creates array of bytes, then converts int32 to the array
        /// </summary>
        /// <param name="value">Int32 value</param>
        /// <param name="bytesNum">Number of bytes </param>
        /// <returns>Array of bytes of size bytesNum.</returns>
        public static byte[] Int32ToBytes(Int32 value, int bytesNum)
        {
            var bytes = new byte[bytesNum];
            for (int i = 0; i < bytesNum; ++i)
            {
                bytes[bytesNum - 1 - i] = (byte)((value & (0xFF << (i << 3))) >> (i * 8));
            }

            return bytes;
        }
        /// <summary>
        /// Converts int32 to byte array
        /// </summary>
        /// <param name="value">Int32 value</param>
        /// <param name="bytes">ArraySegment array to fill</param>
        public static void Int32ToBytes(Int32 value, ArraySegment<byte> bytes)
        {
            for (int i = 0; i < bytes.Count; ++i)
            {
                bytes.Array[bytes.Count - 1 - i + bytes.Offset] = (byte)((value & (0xFF << (i << 3))) >> (i * 8));
            }
        }
}

Related Tutorials