c#从左到右移位16位

本文关键字:16位 右移 | 更新日期: 2023-09-27 18:12:14

我有一个8位的数组,表示如下。Data[i] = 192=11000000, data[i+1]= 85=01010101,我需要将表示转换成16位数组,其中newArr[i] =343=101010111。相同的数字只是向右移动了。我的第一个想法是使用i have bpp(位数=10)字段。所以是var t=16-10Data[i] >>tData[i+1]>>t然而,这并没有给出正确的答案。请帮助

c#从左到右移位16位

我为您准备了这两个函数,用于在字节数组中移位:

static public void ShiftLeft(this byte[] data, int count, bool rol)
{
    if ((count <0) || (count > 8))
        throw new ArgumentException("Count must between 0 and 8.");
    byte mask = (byte)(0xFF << (8 - count));
    int bits = rol ? data[0] & mask : 0;
    for (int i = data.Length - 1; i >= 0; i--)
    {
        int b = data[i] & mask;
        data[i] = (byte)((data[i] << count) | (bits >> (8 - count)));
        bits = b;
    }
}
static public void ShiftRight(this byte[] data, int count, bool rol)
{
    if ((count <0) || (count > 8))
        throw new ArgumentException("Count must between 0 and 8.");
    byte mask = (byte)(0xFF >> (7 - count));
    int bits = rol ? data[data.Length - 1] & mask : 0;
    for (int i = 0; i < data.Length; i++)
    {
        int b = data[i] & mask;
        data[i] = (byte)((data[i] >> count) | (bits << (8 - count)));
        bits = b;
    }
}

对于您的代码示例,这样调用它们:

byte[] data = ...;
ShiftLeft(data, 2, false);

假设您想将2个字节复制到1个ushort中,您可以使用以下代码(确保它的长度是偶数!):

byte[] data = ...;
short[] sdata = new short[data.Length / 2];
Buffer.BlockCopy(data, 0, sdata, 0, dataLen);

如果你想将1个字节复制到1个ushort中,那么这将是答案:

byte[] data = ...;
short[] sdata = Array.ConvertAll(data, b => (short)b);

我认为你的问题是指你想做这个转换:将aaaaaaaabbbbbbbb组合成bbbbbbbbaaaaaaaa,然后右移6,产生000000bbbbbbbbaa

那么这将是你的代码:

using System;
public class Test
{
  public static void Main()
  {
    byte[] src = new byte[2] { 192, 85 };
    ushort[] tgt = new ushort[1];
    for ( int i = 0 ; i < src.Length ; i+=2 )
    {
      tgt[i] = (ushort)( ( src[i+1]<<8 | src[i] )>>6 );
    }
    System.Console.WriteLine( tgt[0].ToString() );
  }
}

如果你想要做的是与aaaabbbbbbbbaa合并,那么这将需要|在第二步中替换src[i]<<10,因为c#中没有循环移位操作符。

我的最终代码:D

 public override short[] GetShortDataAlignedRight()
    {
        short[] ReturnArray = new short[_channels[0].Data.Length / 2];
        if (_channels[0].Bpp == 8)
        {
            Buffer.BlockCopy(_channels[0].Data, 0, ReturnArray, 0, _channels[0].Data.Length);
        }
        else
        {
            short tempData;
            int offsetHigh = 8 - (16 - _channels[0].Bpp);
            int offsetLow = (16 - _channels[0].Bpp);
            for (int i = 0, j = 0; i < _channels[0].Data.Length; i += 2, j++)
            {
                tempData = (short)(_channels[0].Data[i] >> offsetLow);
                tempData |= (short)(_channels[0].Data[i + 1] << offsetHigh);
                ReturnArray[j] = tempData;
            }
        }
        return ReturnArray;
    }