C# how to read first 4 and last 4 bits from byte ?
In a convenient struct:
var hb = new HalvedByte(5, 10);
hb.Low -= 3;
hb.High += 3;
Console.Write(string.Format("{0} / {1}", hb.Low, hb.High));
// 2, 13
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);
}
}
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];
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With