Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A possibly silly question about "custom" integers in C#

Tags:

c#

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.

like image 972
Miguel Avatar asked Oct 28 '10 13:10

Miguel


2 Answers

Build a struct that takes a 32 bit integer and bit masks it with
0000 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..

like image 160
Charles Bretana Avatar answered Oct 18 '22 13:10

Charles Bretana


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.

like image 37
Vincent Ramdhanie Avatar answered Oct 18 '22 13:10

Vincent Ramdhanie