Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read first 4 and last 4 bits from byte?

Tags:

c#

byte

bit

C# how to read first 4 and last 4 bits from byte ?

like image 288
Alexander Avatar asked Apr 09 '13 10:04

Alexander


1 Answers

In a convenient struct:

Usage

var hb = new HalvedByte(5, 10);
hb.Low -= 3;
hb.High += 3;
Console.Write(string.Format("{0} / {1}", hb.Low, hb.High));
// 2, 13

Code

public struct HalvedByte
{
    public byte Full { get; set; }

    public byte Low
    {
        get { return (byte)(Full & 0x0F); }

        set
        {
            if (value >= 16)
            {
                throw new ArithmeticException("Value must be between 0 and 16."); 
            }

            Full = (byte)((High << 4) | (value & 0x0F));
        }
    }

    public byte High
    {
        get { return (byte)(Full >> 4); }

        set
        {
            if (value >= 16)
            {
                throw new ArithmeticException("Value must be between 0 and 16.");
            }

            Full = (byte)((value << 4) | Low);
        }
    }

    public HalvedByte(byte full)
    {
        Full = full;
    }

    public HalvedByte(byte low, byte high)
    {
        if (low >= 16 || high >= 16)
        {
            throw new ArithmeticException("Values must be between 0 and 16.");
        }

        Full = (byte)((high << 4) | low);
    }
}

Bonus: Array (Untested)

If you ever need to use an array of these half bytes, this will simplify accessing:

public class HalvedByteArray
{
    public int Capacity { get; private set; }
    public HalvedByte[] Array { get; private set; }

    public byte this[int index]
    {
        get
        {
            if (index < 0 || index >= Capacity)
            {
                throw new IndexOutOfRangeException();
            }

            var hb = Array[index / 2];

            return (index % 2 == 0) ? hb.Low : hb.High;
        }
        set
        {
            if (index < 0 || index >= Capacity)
            {
                throw new IndexOutOfRangeException();
            }

            var hb = Array[index / 2];

            if (index % 2 == 0)
            {
                hb.Low = value;
            }
            else
            {
                hb.High = value;
            }
        }
    }

    public HalvedByteArray(int capacity)
    {
        if (capacity < 0)
        {
            throw new ArgumentException("Capacity must be positive.", "capacity");
        }

        Capacity = capacity;
        Array = new HalvedByte[capacity / 2];
    }
}
like image 121
Lazlo Avatar answered Sep 21 '22 22:09

Lazlo