Skip to content

Instantly share code, notes, and snippets.

@szehetner
Created September 13, 2018 13:58
Show Gist options
  • Save szehetner/dab144926f1f1e1648ee342e47bf86d4 to your computer and use it in GitHub Desktop.
Save szehetner/dab144926f1f1e1648ee342e47bf86d4 to your computer and use it in GitHub Desktop.
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.InteropServices;
using BenchmarkDotNet.Attributes;
namespace TestApp
{
[MemoryDiagnoser]
public class DecimalConverter
{
decimal value = 123.567m;
private ulong _a;
private ulong _low;
private ulong _b;
private uint _high;
private uint _signScale;
[Benchmark(Baseline = true)]
public void GetBits()
{
int[] bits = decimal.GetBits(value);
_a = ((ulong)bits[1]) << 32;
_b = ((ulong)bits[0]) & 0xFFFFFFFFL;
_low = _a | _b;
_high = (uint)bits[2];
_signScale = (uint)(((bits[3] >> 15) & 0x01FE) | ((bits[3] >> 31) & 0x0001));
}
[Benchmark]
public void StructConversion()
{
var dec = new DecimalAccessor(value);
_a = ((ulong)dec.Mid) << 32;
_b = ((ulong)dec.Lo) & 0xFFFFFFFFL;
_low = _a | _b;
_high = (uint)dec.Hi;
_signScale = (uint)(((dec.Flags >> 15) & 0x01FE) | ((dec.Flags >> 31) & 0x0001));
}
[StructLayout(LayoutKind.Explicit)]
public struct DecimalAccessor
{
[FieldOffset(0)]
public int Flags;
[FieldOffset(4)]
public int Hi;
[FieldOffset(8)]
public int Lo;
[FieldOffset(12)]
public int Mid;
[FieldOffset(0)]
public decimal Decimal;
public DecimalAccessor(decimal value)
{
Flags = 0;
Hi = 0;
Lo = 0;
Mid = 0;
Decimal = value;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment