从左到右C位移位16位C#

时间:2013-05-04 22:18:12

标签: c# bit-manipulation

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

3 个答案:

答案 0 :(得分:2)

我有这两个函数,转换为字节数组:

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);

答案 1 :(得分:1)

我认为您要进行此转换:将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#中没有循环移位运算符。

答案 2 :(得分:0)

我的最终代码: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;
    }