Good afternoon,
This may sound like a silly question, but it would be really useful if there was a way around this... Is there any way I can get custom bit-depth integers (for example, a 20-bit integer) in C#?
Thank you very much.
Build a struct that takes a 32 bit integer and bit masks it with0000 0000 0000 1111 1111 1111 1111 1111
, or (0x08FF
)
before storing it in an internal private field.
public struct TwentyBitInt
{
private const int mask = 0x08FF;
private int val;
private bool isDef;
private TwentyBitInt(int value)
{
val = value & mask;
isDef = true;
}
public static TwentyBitInt Make(int value)
{ return new TwentyBitInt(value); }
public int Value { get { return val; } }
public bool HasValue { get { return isDef; } }
public static TwentyBitInt Null = new TwentyBitInt();
public static explicit operator int (TwentyBitInt twentyBit)
{
if (!HasValue) throw new ArgumentNullValueException();
return twentyBit.val;
}
public static implicit operator TwentyBitInt (int integerValue)
{ return Make(integerValue); }
// etc.
}
You can also appropriately overload the arithmetic operators so that arithmetic operations behave consistently with the business rules for the domain they are to be used in..
I think you can but it is not going to be easy. You can use something like a BitArray to create an arbitrary length bitstring. Then you have to write all the code yourself to treat it like an integer. That's the hard part.
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