Binary Serialization of decimal types

C

Chris Holmes

I'm working on an application where we need to persist
decimal values on a PocketPC device, but the Compact
Framework doesn't support decimal types in the BinaryWriter/
BinaryReader classes, or even in the BitConverter class.

Is there some nice, happy way to convert a decimal into
it's byte array equivalent through the framework?

At the moment, I'm accomplishing the task by using some
unsafe code that looks like this:

public byte[] Serialize( decimal d ) {
byte[] data = new byte[16]; // decimals being 16 bytes
fixed( byte *ptr = data ) {
*(decimal *)ptr = d;
}
return data;
}

Deserialization works almost exactly the same way.

Is there a better way to do this conversion, and are there
any problems with this particular method of doing the
conversion? I really don't understand why every type but
decimal is supported throughout the Compact Framework.

Thanks much,
Chris
 
J

João Paulo Figueira [eMVP]

Try this:
using System.Data.SqlTypes;

public static byte[] GetBytes(Decimal d)

{

SqlDecimal sqld = new SqlDecimal(d);

return sqld.BinData;

}
 
C

Chris Holmes

Well, that's a little on the hackish side (not that my solution isn't
completely on the hackish side), but it definitely works.

Is there anything particularly wrong with the unsafe code method I
listed above though?

Chris
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top