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

24,034

Solution 1

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

Solution 2

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

Solution 3

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);
}
Share:
24,034

Related videos on Youtube

Rodney S. Foley
Author by

Rodney S. Foley

If you are writing code and not writing properly maintainable unit tests then you are writing buggy and difficult to maintain code.

Updated on July 09, 2022

Comments

  • Rodney S. Foley
    Rodney S. Foley almost 2 years

    I am looking to learn how to get two nibbles (high and low) from a byte using C# and how to assembly 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.

  • Sandra
    Sandra almost 14 years
    this solution works very well if the OP wants to mask and convert to purely 4 bit values which is often times the case.
  • Ben Voigt
    Ben Voigt almost 11 years
    Simpler: (value >> nibblePos) & 0x0F
  • xnr_z
    xnr_z over 7 years
    What does it mean if the assertion is not True?
  • WorkingRobot
    WorkingRobot over 6 years
    @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.