[英]C# binary array to decimal?
In SQL, the following works cast([comlum] as Decimal(18,4))
在SQL中,以下工作
cast([comlum] as Decimal(18,4))
How can I do the same conversion (from the binary data) in C#? 如何在C#中执行相同的转换(从二进制数据)?
the data type of varbinary in SQL C# loading to byte[] so, I want to byte[] convert to decimal or double? SQL C#中varbinary的数据类型加载到byte [],因此,我想将byte []转换为十进制或双精度吗?
Sql query: select cast([column_A] as decimal(18,4), [column_A] from table
SQL查询:
select cast([column_A] as decimal(18,4), [column_A] from table
result: 191128.0000 0x1204000180D1EB71 结果:191128.0000 0x1204000180D1EB71
I hope to get value as 191128.0000
in C# 我希望在C#中获得
191128.0000
价值
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: 要将字节数组转换为C#小数,反之亦然,您可以使用以下代码:
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[]
? 它是一个以
byte[]
表示的现有decimal
吗? Unlike things like float
/ double
, there is no common/shared understanding of decimal
as byte[]
. 与
float
/ double
类的东西不同,对decimal
作为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; 但是,如果它是 .NET
decimal
,则可以使用new decimal(int[])
的重载-但是您需要首先将字节打包为int; which means you need to know the endianness... 这意味着您需要了解字节序...
Or is the array actually a double
? 还是数组实际上是
double
精度数组? In which case, BitConverter
should help. 在这种情况下,
BitConverter
应该会提供帮助。
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). 已经看到了更新的问题,我怀疑你将不得不施放此数据(TSQL)它出来的SQL Server 之前 ,或挖出用于包装在SQL Server中的数据实现专用的编码(也就是会很脆弱,并且IMO可能不应该离开服务器)。 There is a
SqlDecimal
type, but this also doesn't accept a byte[]
. 有一个
SqlDecimal
类型,但是这也不能接受byte[]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.