将字节数组移N位 [英] Bit-shifting a byte array by N bits

查看:64
本文介绍了将字节数组移N位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,关于移位的问题

我有一个十六进制值:new byte[] { 0x56, 0xAF }; 这是0101 0110 1010 1111

I have a value in HEX: new byte[] { 0x56, 0xAF }; which is 0101 0110 1010 1111

我要前N位,例如12.

I want to the first N bits, for example 12.

然后我必须右移最低的4位(16-12)以获得0000 0101 0110 1010(dec 1386).

Then I must right-shift off the lowest 4 bits (16 - 12) to get 0000 0101 0110 1010 (1386 dec).

我无法将其包裹住并使它可扩展n位.

I can't wrap my head around it and make it scalable for n bits.

推荐答案

有时候我对这两个函数进行了编码,第一个将byte []左移指定的位数,第二个向右移:

Sometime ago i coded these two functions, the first one shifts an byte[] a specified amount of bits to the left, the second does the same to the right:

左移:

public byte[] ShiftLeft(byte[] value, int bitcount)
{
    byte[] temp = new byte[value.Length];
    if (bitcount >= 8)
    {
        Array.Copy(value, bitcount / 8, temp, 0, temp.Length - (bitcount / 8));
    }
    else
    {
        Array.Copy(value, temp, temp.Length);
    }
    if (bitcount % 8 != 0)
    {
        for (int i = 0; i < temp.Length; i++)
        {
            temp[i] <<= bitcount % 8;
            if (i < temp.Length - 1)
            {
                temp[i] |= (byte)(temp[i + 1] >> 8 - bitcount % 8);
            }
        }
    }
    return temp;
}

右移

public byte[] ShiftRight(byte[] value, int bitcount)
{
    byte[] temp = new byte[value.Length];
    if (bitcount >= 8)
    {
        Array.Copy(value, 0, temp, bitcount / 8, temp.Length - (bitcount / 8));
    }
    else
    {
        Array.Copy(value, temp, temp.Length);
    }
    if (bitcount % 8 != 0)
    {
        for (int i = temp.Length - 1; i >= 0; i--)
        {
            temp[i] >>= bitcount % 8;
            if (i > 0)
            {
                temp[i] |= (byte)(temp[i - 1] << 8 - bitcount % 8);
            }
        }
    }
    return temp;
}

如果您需要进一步的解释,请对此发表评论,然后我将编辑我的帖子以进行澄清...

If you need further explanation please comment on this, i will then edit my post for clarification...

这篇关于将字节数组移N位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆