1

In SQL, the following works cast([comlum] as Decimal(18,4))

How can I do the same conversion (from the binary data) in C#?


the data type of varbinary in SQL C# loading to byte[] so, I want to byte[] convert to decimal or double?

Sql query: select cast([column_A] as decimal(18,4), [column_A] from table

result: 191128.0000      0x1204000180D1EB71

I hope to get value as 191128.0000 in C#


Because, I use entity framework
so, have this question

1
  • I updated my answer to take your update into account. Commented Jan 19, 2010 at 7:36

2 Answers 2

4

To cast a byte array to a C# decimal and vice versa you might use this piece of code:

decimal d = 12.3456789m;

// decimal to byte[]
byte[] bytes = new byte[16];
Buffer.BlockCopy(decimal.GetBits(d), 0, bytes, 0, 16);

// byte[] to decimal
int[] bits = new int[4];
Buffer.BlockCopy(bytes, 0, bits, 0, 16);
Console.WriteLine(new decimal(bits));  // 12.3456789
Sign up to request clarification or add additional context in comments.

Comments

3

Well, what does the binary array contain? Is it an existing decimal represented as a byte[]? Unlike things like float / double, there is no common/shared understanding of decimal as byte[].

But if it is a .NET decimal you could use the overload of new decimal(int[]) - but you'll need to pack the bytes into ints first; which means you need to know the endianness...

Or is the array actually a double? In which case, BitConverter should help.


Having seen the update to the question, I suspect that you are going to have to cast this data (in TSQL) before it comes out of SQL Server, or dig out the implementation-specific encoding used to pack the data in SQL Server (which would be brittle, and IMO probably shouldn't leave the server). There is a SqlDecimal type, but this also doesn't accept a byte[].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.