(C#ベース)byte[]の初期化、値付け、変換.

12353 ワード

byte[]の初期化付与
for loopで値を付けるのはもちろん基本的な方法ですが、C#には他にも便利な方法があります.
1.長さ10のbyte配列を作成し、各byteの値は0である.
byte[] myByteArray = new byte[10];

C#数値型(int,byte)配列を作成すると、配列内の各要素は自動的に0に割り当てられます.(注:string[]の場合、各要素の値はnullです.
 
2.長さ10のbyte配列を作成し、各byteの値は0 x 08である. 
byte[] myByteArray = Enumerable.Repeat((byte)0x08, 10).ToArray();

linqで値を割り当てます.文は1つだけです.もちろん、私たちは異なる値を割り当てることができますが、一定の規則的な値があります.
byte[] res= Enumerable.Range(1, 1000).Select(c=>Convert.ToByte(c)).ToArray();

 
3.直接賦課
byte[] myByteArray = new byte[] { 0x01, 0x02, 0x03 };

 
byte[] ---> ushort
            byte[] array = new byte[] { 0xFE, 0x00 };



            ushort register = BitConverter.ToUInt16(array, 0);

上記変換後のregisterの値は0 x 00 FE
            byte[] array = new byte[] { 0x02, 0x01 ,0x04, 0x03 };



            ushort register = BitConverter.ToUInt16(array, 0);

上記転化後、実はarray[0]、array[1]を取っただけである.の値で、最後のregisterの値は0 x 00010002、つまり258です.
byte[] -> string
public static string ByteArrayToString(byte[] ba)

{

  string hex = BitConverter.ToString(ba);

  return hex.Replace("-","");

}

 
ushort ---> byte[]
            ushort register = 0x00F0;



            byte[] arr = BitConverter.GetBytes(register); 

PCシステムではarr[0]=0 xF 0(地位)、arr[1]=0 x 00. 
UShortの2バイトを交換
            ushort number = 0x00F0;



            byte[] temp = BitConverter.GetBytes(number);

            Array.Reverse(temp); 



            ushort a = BitConverter.ToUInt16(temp, 0);



            ushort b = (ushort)(number << 8 | ((number & 0xFF00) >> 8));

 byte[] => Struct
public StructType ConverBytesToStructure<StructType>(byte[] bytesBuffer)

        {

            //

            if (bytesBuffer.Length != Marshal.SizeOf(typeof(StructType)))

            {

                throw new ArgumentException("bytesBuffer structObject 。");

            }



            IntPtr bufferHandler = Marshal.AllocHGlobal(bytesBuffer.Length);

            for (int index = 0; index < bytesBuffer.Length; index++)

            {

                Marshal.WriteByte(bufferHandler, index, bytesBuffer[index]);

            }

            StructType structObject = (StructType)Marshal.PtrToStructure(bufferHandler, typeof(StructType));

            Marshal.FreeHGlobal(bufferHandler);

            return structObject;

        }
 



     /// <summary>

        ///  byte[] struct, 

        /// startIndex:  Copy  。

        /// length: 。

        /// </summary>

        public static T BytesToStruct<T>(byte[] bytes, int startIndex, int length)

        {

            if (bytes == null) return default(T);

            if (bytes.Length <= 0) return default(T);

            IntPtr buffer = Marshal.AllocHGlobal(length);

            try//struct_bytes 

            {

                Marshal.Copy(bytes, startIndex, buffer, length);

                return (T)Marshal.PtrToStructure(buffer, typeof(T));

            }

            catch(Exception ex)

            {

                throw new Exception("Error in BytesToStruct ! " + ex.Message);

            }

            finally

            {

                Marshal.FreeHGlobal(buffer);

            }

        }

Struct => byte[]
  



     /// <summary>

        ///  struct byte[]

        /// </summary>

        public static byte[] StructToBytes(object structObj, int size)

        {

            IntPtr buffer = Marshal.AllocHGlobal(size);

            try//struct_bytes 

            {

                Marshal.StructureToPtr(structObj, buffer, false);

                byte[] bytes = new byte[size];

                Marshal.Copy(buffer, bytes, 0, size);

                return bytes;

            }

            catch (Exception ex)

            {

                throw new Exception("Error in StructToBytes ! " + ex.Message);

            }

            finally

            {

                Marshal.FreeHGlobal(buffer);

            }

        }

 
byte[]配列比較
//You can use Enumerable.SequenceEqual method.



using System;

using System.Linq;

...

var a1 = new int[] { 1, 2, 3};

var a2 = new int[] { 1, 2, 3};

var a3 = new int[] { 1, 2, 4};

var x = a1.SequenceEqual(a2); // true

var y = a1.SequenceEqual(a3); // false

 
参照:http://www.dotnetperls.com/initialize-array