位移N位

你好关于位移的快速问题

我有一个HEX = new byte [] {0x56,0xAF}的值;

这是0101 0110 1010 1111

我想要前n位,例12

然后转移剩下的4(16-12)得到0000 0101 0110 1010(1386 dec)

我无法绕过它并使其可扩展到n位。

谢谢!

前段时间我编写了这两个函数,第一个将一个字节[]向左移动指定的位数,第二个向右移动:

左移:

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

如果您需要进一步说明,请对此进行评论,然后我会编辑我的post以澄清...

您可以使用BitArray,然后从右侧开始轻松将每个位复制到右侧。

http://msdn.microsoft.com/en-us/library/system.collections.bitarray_methods.aspx

你想要像…

 var HEX = new byte[] {0x56, 0xAF}; var bits = new BitArray(HEX); int bitstoShiftRight = 4; for (int i = 0; i < bits.Length; i++) { bits[i] = i < (bits.Length - bitstoShiftRight) ? bits[i + bitstoShiftRight] : false; } bits.CopyTo(HEX, 0); 

如果你有总共k位,并且你想要“第一”(如最重要的那样)n位,你可以简单地右移kn次。 最后的kn位将被移除,通过从末端“下降”的类型,并且第一个n将被移动到最不重要的一侧。

假设bits_in_byte是在别处确定的字节中的位数,则使用类似C的表示法回答:

 int remove_bits_count= HEX.count*bits_in_byte - bits_to_keep; int remove_bits_in_byte_count= remove_bits_count % bits_in_byte; if (remove_bits_count > 0) { for (int iteration= 0; iteration=0) { int read_index_hi= read_index_lo - (remove_bits_count + bits_in_byte - 1)/bits_in_byte; HEX[write_index]= (HEX[read_index_lo] >> remove_bits_in_byte_count) | (HEX[read_index_hi] << (bits_in_byte - remove_bits_in_byte_count)); } else { HEX[write_index]= 0; } } } 

假设你要覆盖原始数组,你基本上把你写的每一个字节都拿出来,并找出它从中获取移位位的字节数。 您从arrays的末尾前进到前面,以确保您永远不会覆盖您需要阅读的数据。