C# Byte数组与Int16数组之间的转换(转)

u

这里提供两个函数,完成相互转换。

        private void Int16ToByte(Int16[] arrInt16, int nInt16Count, ref Byte[] destByteArr)
        {
            //高字节放在前面,低字节放在后面
            for (int i = 0; i < nInt16Count; i++ )
            {
                destByteArr[2 * i + 0] = Convert.ToByte((arrInt16[i] & 0xFF00) >> 8);
                destByteArr[2 * i + 1] = Convert.ToByte((arrInt16[i] & 0x00FF));
            }
        }

        private void ByteToInt16(Byte[] arrByte, int nByteCount, ref Int16[] destInt16Arr)
        {
            //按两个字节一个整数解析,前一字节当做整数高位,后一字节当做整数低位
            for (int i = 0; i < nByteCount / 2; i++)
            {
                destInt16Arr[i] = Convert.ToInt16(arrByte[2 * i + 0] << 8 + arrByte[2 * i + 1]);
            }
        }

using System;

int  i = 123;
byte [] intBuff = BitConverter.GetBytes(i);     // 将 int 转换成字节数组
lob.Write(intBuff, 0, 4);
i = BitConverter.ToInt32(intBuff, 0);           // 从字节数组转换成 int

double x = 123.456;
byte [] doubleBuff = BitConverter.GetBytes(x);  // 将 double 转换成字节数组
lob.Write(doubleBuff, 0, 8);
x = BitConverter.ToDouble(doubleBuff, 0);       // 从字节数组转换成 double

原文地址:https://www.cnblogs.com/xihong2014/p/14989847.html