How to convert byte[] to decimal[] in C#

239 views
Skip to first unread message

wigzell

unread,
Nov 24, 2009, 11:16:21 AM11/24/09
to DotNetDevelopment, VB.NET, C# .NET, ADO.NET, ASP.NET, XML, XML Web Services,.NET Remoting
In C#, I create a byte[] using BinaryFormatter etc. as follows:

decimal[] theArray = new decimal[2];
theArray[0] = (decimal) 36300288.734436237;
theArray[1] = (decimal) 34176522.502899267;
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, theArray);
byte[] bytes = ms.GetBuffer();

This is then stored to SQL Server 2005 in varbinary field. When
loading this from SQL, I get the byte[] back - so my question is, how
do I convert the byte[] back to the decimal[]?

Many thanks,
Cathy

Cerebrus

unread,
Nov 25, 2009, 1:15:30 AM11/25/09
to DotNetDevelopment, VB.NET, C# .NET, ADO.NET, ASP.NET, XML, XML Web Services,.NET Remoting
What's wrong with BinaryFormatter.Deserialize() ?

Processor Devil

unread,
Nov 25, 2009, 3:09:21 AM11/25/09
to dotnetde...@googlegroups.com
what about the old way?

        public static decimal[] Bytes2Decimal(byte[] bytes)
        {
            decimal[] toReturn = new decimal[bytes.Length];
            for(int i = 0; i < bytes.Length; i++)
                toReturn[i] = Convert.ToDecimal(bytes[i]);
            return toReturn;
        }

2009/11/25 Cerebrus <zor...@sify.com>

Cerebrus

unread,
Nov 25, 2009, 5:06:12 AM11/25/09
to DotNetDevelopment, VB.NET, C# .NET, ADO.NET, ASP.NET, XML, XML Web Services,.NET Remoting
Posted a quick and dirty example here:

<http://dotnetdevelopment.pastebin.com/f4e18ab21>

On Nov 25, 1:09 pm, Processor Devil <processor.de...@gmail.com> wrote:
> what about the old way?
>
>         public static decimal[] Bytes2Decimal(byte[] bytes)
>         {
>             decimal[] toReturn = new decimal[bytes.Length];
>             for(int i = 0; i < bytes.Length; i++)
>                 toReturn[i] = Convert.ToDecimal(bytes[i]);
>             return toReturn;
>         }
>
> 2009/11/25 Cerebrus <zorg...@sify.com>

Cerebrus

unread,
Nov 25, 2009, 5:27:37 AM11/25/09
to DotNetDevelopment, VB.NET, C# .NET, ADO.NET, ASP.NET, XML, XML Web Services,.NET Remoting
Two points to make:

1. MemoryStream.GetBuffer() is not my preferred method because it
creates a default sized buffer (256) even when not needed. I prefer to
Read() the memorystream into a byte[] buffer with demarcated length,
instead.

2. Your example does not work because it creates a decimal array with
the same no. of items as in the byte array. In my test, it creates a
decimal array with 66 items. However, the original array has only 2
items.
Reply all
Reply to author
Forward
0 new messages