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 using C# and .NET 4.0 if that helps with what methods can be done and what libraries may be available.

Amal K
  • 4,359
  • 2
  • 22
  • 44
Rodney S. Foley
  • 10,190
  • 12
  • 48
  • 66

4 Answers4

36

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);
Shimmy Weitzhandler
  • 101,809
  • 122
  • 424
  • 632
Mau
  • 14,234
  • 2
  • 31
  • 52
  • this solution works very well if the OP wants to mask and convert to purely 4 bit values which is often times the case. – Firoso Jun 26 '10 at 18:12
5

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);
}
Shimmy Weitzhandler
  • 101,809
  • 122
  • 424
  • 632
5

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
Daniel
  • 61
  • 1
  • 1
0

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.
Shimmy Weitzhandler
  • 101,809
  • 122
  • 424
  • 632
Firoso
  • 6,647
  • 10
  • 45
  • 91
  • What does it mean if the assertion is not True? – xnr_z Dec 22 '16 at 12:18
  • @krvl it means that there was some sort of error. If that assertion is false, then that means that the high nibble combined with the low nibble is not equal to the original byte. If that's the case, then there would be some sort of error in the calculations. – WorkingRobot Nov 19 '17 at 18:24