2010-06-26 16 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