你怎么能在C#中蚕食(nybble)字节?

我想学习如何使用C#从一个字节中获取两个半字节(高和低)以及如何将两个半字节组装回一个字节。

我正在使用C#和.Net 4.0,如果这有助于可以使用哪些方法以及可以使用哪些库。

您可以“屏蔽”一个字节的4位以使用半字节,然后将这些位移到字节中最右侧的位置:

byte x = 0xA7; // For example... byte nibble1 = (byte) (x & 0x0F); byte nibble2 = (byte)((x & 0xF0) >> 4); // Or alternatively... nibble2 = (byte)((x >> 4) & 0x0F); byte original = (byte)((nibble2 << 4) | nibble1); 

这个扩展做了OP要求的,我想为什么不分享它:

 ///  /// Extracts a nibble from a large number. ///  /// Any integer type. /// The value to extract nibble from. /// The nibble to check, /// where 0 is the least significant nibble. /// The extracted nibble. public static byte GetNibble(this T t, int nibblePos) where T : struct, IConvertible { nibblePos *= 4; var value = t.ToInt64(CultureInfo.CurrentCulture); return (byte)((value >> nibblePos) & 0xF); } 

我想你可以做一些按位操作

 byte nib = 163; //the byte to split byte niblow = nib & 15; //bitwise AND of nib and 0000 1111 byte nibhigh = nib & 240; //bitwise AND of nib and 1111 0000 Assert.IsTrue(nib == (nibhigh | niblow)); //bitwise OR of nibhigh and niblow equals the original nib. 

没有一个答案令人满意,所以我会提交自己的答案。 我对这个问题的解释是:
输入:1字节(8位)
输出:2个字节,每个存储一个半字节,意味着4个最左边的位(又名高半字节)是0000,而最右边的4个位(低半字节)包含分离的半字节。

 byte x = 0x12; //hexadecimal notation for decimal 18 or binary 0001 0010 byte highNibble = (byte)(x >> 4 & 0xF); // = 0000 0001 byte lowNibble = (byte)(x & 0xF); // = 0000 0010