2010-06-26 41 views

回答

27

可以“屏蔽掉”一个字节的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); 
+0

这个解决方案工作得非常好,如果日OP要掩盖并转换为纯粹的4位值,这往往是这种情况。 – Firoso 2010-06-26 18:12:34

0

我会假设你可以做一些位操作

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. 
+0

如果断言不是真的,这意味着什么? – krvl 2016-12-22 12:18:04

+0

@krvl这意味着有某种错误。如果该断言是错误的,那么这意味着高半字节与低半字节组合不等于原始字节。如果是这种情况,那么计算中会出现某种错误。 – ProgramFast 2017-11-19 18:24:50

2

这个扩展做什么的任择议定书的要求,我想为什么不分享:

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

简单:'(value >> nibblePos)&0x0F' – 2013-05-19 01:43:47

+0

@ BenVoigt,你是对的。更新。谢谢。 – Shimmy 2013-05-19 01:49:54