Byte Array from DateTime Array

  • Thread starter Thread starter Daniel
  • Start date Start date
D

Daniel

I'm trying to serialize a DateTime [] into a Byte []. Buffer.BlockCopy
doesn-t work because DateTime is not a primitive type.
Is there a way to cast from DateTime [] to Byte [] in the "safe" world?
 
In .NET 2.0 there is a method DateTime.ToBinary(...)

In .NET 1.1 you use DateTime.ToFileTimeMethod()
 
Yes, I was aware of those methods, but it will involve a for loop to get
the Binary value of each item in the array. As I'm looking to persist a
Byte [] array as fast as possible, I was looking for a direct method of
accessing the DateTime [] as Byte [].
(My underlying problem is to persist big amounts of DateTimes in a
Database. Instead of generating one db record per value, I prefer to
store a binary serialization in a BLOB field).
With doubles this is easy due to Buffer.BlockCopy. But i was unable to
find a fast alternative for my DateTime arrays.
Txs
 
"accessing the DateTime [] as Byte []" you mean the access like in stream?
You can use Ticks property instead of GetFileTime(...). Then it will not be
necessary to
perform any conversions ( all datetime time/date props are based on ticks),
simply:
-get DateTime from array
-write Ticks into byte[] ( MemoryStream is better for such operations )
 
Daniel said:
Yes, I was aware of those methods, but it will involve a for loop to get
the Binary value of each item in the array. As I'm looking to persist a
Byte [] array as fast as possible, I was looking for a direct method of
accessing the DateTime [] as Byte [].
(My underlying problem is to persist big amounts of DateTimes in a
Database. Instead of generating one db record per value, I prefer to
store a binary serialization in a BLOB field).
With doubles this is easy due to Buffer.BlockCopy. But i was unable to
find a fast alternative for my DateTime arrays.

When you say you were unable to find a "fast" alternative - have you
benchmarked the "simple" solution of iterating through the array? I
suspect you'll find that fast enough.

I would suggest you use the Ticks property to convert each DateTime to
a long. There are various ways you can then get this into a byte array.
To save creating a load of small byte arrays, you might want to use my
miscellaneous utility library's EndianBitConverter which has CopyBytes
as well as GetBytes, to copy the converted value into an existing byte
array.
You can download the library from
http://www.pobox.com/~skeet/csharp/miscutil
 
Back
Top