Well, I don’t think you need to use floating point ...
public static int Add(int a, int b) { int firstWhole = a / 1000; int secondWhole = b / 1000; int firstFraction = a % 1000; int secondFraction = b % 1000; int totalFraction = firstFraction + secondFraction; int totalWhole = firstWhole + secondWhole + (totalFraction / 320); return totalWhole * 1000 + (totalFraction % 320); }
Alternatively, you may need to create a custom structure that can convert to and from your integer format, and overloads the + operator. This would allow you to write more readable code that would not accidentally cause other integers to be processed as this odd format.
EDIT: If you are forced to adhere to the “one whole” format, but you can tweak it a bit, you might want to use 512 instead of 1000. So you can use a simple mask and shift:
public static int Add(int a, int b) { int firstWhole = a >> 9; int secondWhole = b >> 9; int firstFraction = a & 0x1ff int secondFraction = b & 0x1ff; int totalFraction = firstFraction + secondFraction; int totalWhole = firstWhole + secondWhole + (totalFraction / 320); return (totalWhole << 9) + (totalFraction % 320); }
There is still a problem with 320, but it is at least somewhat better.
Jon skeet
source share