开发者

C# binary array to decimal?

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), [colum开发者_运维问答n_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


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


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[].

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜