位移N位 [英] Bit shifting N bits
问题描述
您好快速的问题关于位移
Hello quick question regarding bit shifting
我在十六进制的值=新的字节[] {0x56,0xAF执行};
I have a value in HEX = new byte[] { 0x56, 0xAF };
这是0101 0110 1010 1111
which is 0101 0110 1010 1111
我想第一n位,例如12
i want to the first n bits, example 12
再推卸其余4(16-12)获得0000 0101 0110 1010(1386 DEC)
then shift off the remaining 4 (16-12) to get 0000 0101 0110 1010 (1386 dec)
我不能换我的头周围并使其可伸缩的N位。
i cant wrap my head around it and make it scalable for n bits.
谢谢!
推荐答案
早前I codeD这两个功能,第一个移位位的字节[]指定金额到左侧,第二次做同样的向右:
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;
}
右Shift:
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屋!