samedi 3 septembre 2016

Turn random bytes to .NET decimal 0..1 fractional range

I'm playing with a TRNG usb device, and successfully turning the random bytes into various usable data in C#.

I'd like to create a .NET decimal value between 0..1 (ex: 0.37327) directly from the bytes using binary reader (or other direct bytes -> decimal) method.

// assume: byte[] random_data of appropriate length, patterned for a 0..1 range decimal value = new BinaryReader(new MemoryStream(random_data)).ReadDecimal();

I was looking for the byte format of decimal, but it looks like it may not be a standard?

This is for hobby work, so it's acceptable to me to use something that might change in future. I've looked at the bytes generated for sample input decimal values - I see negative and precision flags (1Ch max in last int32?), but the min/max data values dumping compiler constants are stumping me a bit, and I'm generate above zero values or invalid values:

  • fractional value nearest 1 (.99...9): FFFFFF0F 6102253E 5ECE4F20 00001C00
  • fractional value nearest 0 (.00...1): 01000000 00000000 00000000 00001C00

Can you help me onto the correct path for generating a full fractional 0..1 range?




Aucun commentaire:

Enregistrer un commentaire