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

有时候,需要类型不同的数组转换,

比如,从采集卡里读出的是Int16类型的数据,需要存储在数据库OLE对象里面,就需要转换成Byte型。

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

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

        private void ByteToInt16(Byte[] arrByte, int nByteCount, ref Int16[] destInt16Arr)
        {
            int i=0;
            try
            {
                //按两个字节一个整数解析,前一字节当做整数低位,后一字节当做整数高位,调用系统函数转化
                for (i = 0; i < nByteCount / 2; i++)
                {
                    Byte[] tmpBytes = new Byte[2] { arrByte[2 * i + 0], arrByte[2 * i + 1] };
                    destInt16Arr[i] = BitConverter.ToInt16(tmpBytes, 0);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("Byte to Int16转化错误!i=" + e.Message + i.ToString());
            }
        }

 

posted on 2017-09-15 16:19  不忘初心,知耻后勇  阅读(2543)  评论(0编辑  收藏  举报

导航