Home Forums SQL Server 2008 T-SQL (SS2K8) Converting varbinary to numeric type in tsql -- decimal in c# RE: Converting varbinary to numeric type in tsql -- decimal in c#

  • Here is the c# code for converting to and from the bytes

    byte[] GetBytes ( decimal? value )

    {

    if ( value == null )

    {

    return null;

    }

    byte[] bytes = new byte[16];

    int[] bits = Decimal.GetBits ( (decimal) value );

    Array.Copy ( BitConverter.GetBytes ( bits[0] ), 0, bytes, 0, 4 );

    Array.Copy ( BitConverter.GetBytes ( bits[1] ), 0, bytes, 4, 4 );

    Array.Copy ( BitConverter.GetBytes ( bits[2] ), 0, bytes, 8, 4 );

    Array.Copy ( BitConverter.GetBytes ( bits[3] ), 0, bytes, 12, 4 );

    return bytes;

    }

    //--------------------

    decimal? ToDecimal ( byte[] value )

    {

    if ( value == null )

    {

    return null;

    }

    int[] bits = { BitConverter.ToInt32 ( value, 0 ), BitConverter.ToInt32 ( value, 4 ), BitConverter.ToInt32 ( value, 8 ), BitConverter.ToInt32 ( value, 12 ) };

    return new decimal ( bits );

    }