Advertisement
Guest User

C# Decimal reinterpret as longs and back

a guest
Sep 24th, 2013
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.21 KB | None | 0 0
  1. using System;
  2. using System.Runtime.InteropServices;
  3.  
  4. namespace Example {
  5.  
  6.    /// <summary>
  7.    /// Each instance must be used in single thread
  8.    /// </summary>
  9.    class DecimalBitConverter {
  10.  
  11.       [StructLayout(LayoutKind.Explicit)]
  12.       struct OverlapData {
  13.          [FieldOffset(0)] public Decimal decimalValue;
  14.          [FieldOffset(0)] public Int64 int64_0;
  15.          [FieldOffset(8)] public Int64 int64_1;
  16.       }
  17.  
  18.       OverlapData _temp = new OverlapData();
  19.  
  20.       public Decimal ToDecimal(Int64 i0, Int64 i1) {
  21.          _temp.int64_0 = i0;
  22.          _temp.int64_1 = i1;
  23.          return _temp.decimalValue;
  24.       }
  25.  
  26.       public Decimal ToDecimal(Tuple<Int64, Int64> x) {
  27.          return ToDecimal(x.Item1, x.Item2);
  28.       }
  29.  
  30.       public Tuple<Int64, Int64> ToLongs(Decimal x) {
  31.          _temp.decimalValue = x;
  32.          return Tuple.Create(_temp.int64_0, _temp.int64_1);
  33.       }
  34.    }
  35.  
  36.    class Test {
  37.       private static void Main(string[] args) {
  38.          var x = 42.0042m;
  39.          var converter = new DecimalBitConverter();
  40.          var t = converter.ToLongs(x);
  41.          Console.WriteLine(t);
  42.          var y = converter.ToDecimal(t);
  43.          Console.WriteLine(y);
  44.       }
  45.    }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement