开发者

How can you nibble (nybble) bytes in C#?

开发者 https://www.devze.com 2023-01-05 07:25 出处:网络
I am looking to learn how to get two nibbles (high and low) from a byte using C#开发者_高级运维 and how to assemble two nibbles back to a byte.

I am looking to learn how to get two nibbles (high and low) from a byte using C#开发者_高级运维 and how to assemble two nibbles back to a byte.

I am using C# and .NET 4.0 if that helps with what methods can be done and what libraries may be available.


You can 'mask off' 4 bits of a byte to have a nibble, then shift those bits to the rightmost position in the byte:

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


None of the answers were satisfactory so I will submit my own. My interpretation of the question was:
Input: 1 byte (8 bits)
Output: 2 bytes, each storing a nibble, meaning the 4 leftmost bits (aka high nibble) are 0000 while the 4 rightmost bits (low nibble) contain the separated nibble.

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


This extension does what the OP requested, I thought why not share it:

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


I would assume you could do some bitwise operations

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号