Convert Double Value to Byte value for storing in SQLite Database
Question
i want to save a byte[] in a table of SQLite Database (Field datatype is BLOB).
In that array i want to save a negative Double value say -36524.063415093093 in byte format (Not in byte[] format)
Double b = -36524.063415093093;
// Signature is
// byte[] arr = new Byte[] {Double, byte, byte, byte};
When i write Convert.ToByte(b) it gives error & if i write (byte)b it returns 84.
but how to i convert 84 back to -36524.063415093093?
Please correct if my approach is wrong?
Solution
Please correct if my approach is wrong?
Your approach is wrong ;-)
You cannot store a double (which requires 64 bits) into a single byte (which is only 8 bits). It's impossible
You can get a byte array, which is just all the 64 bits spread across 8 bytes. This would let you store your double in a byte array. But you indicate that you don't want that.
OTHER TIPS
From MSDN:
The double keyword denotes a simple type that stores 64-bit floating-point values
So, you will get the array of bytes when you will convert double
to byte[]
. Conversion itself will looks like:
byte[] array = BitConverter.GetBytes(double)
A double uses 8 bytes of memory so you will probably need to convert it into a byte array using the BitConverter class.
but how to i convert 84 back to -36524.063415093093?
You can't. The reason you're getting 84 is that the conversion from double
to byte
discards information:
- Conversion to an integer discards the fractional part of the number, leaving -36524 (0xffff7154).
- Truncation to
byte
discards all but the last 8 bits, leaving 0x54, or 84.
There's no way to reconstruct the original value. How would your decoding routine know that you meant -36524.063415093093 instead of 84.0 or 2132.9?
If you want to store a double
in a database, you need to store all 64 bits of it, not just 8 bits. The easiest way to do this would be to use a REAL
column instead of encoding your data as a BLOB
.
If you have a reason to use a BLOB
, then please explain what it is.
It's possible to convert a double to bytes and back with a helper struct with explicit layout.
[StructLayout(LayoutKind.Explicit)]
public struct DoubleStruct
{
[FieldOffset(0)]
public double value;
[FieldOffset(0)]
public byte byte0;
[FieldOffset(1)]
public byte byte1;
[FieldOffset(2)]
public byte byte2;
[FieldOffset(3)]
public byte byte3;
[FieldOffset(4)]
public byte byte4;
[FieldOffset(5)]
public byte byte5;
[FieldOffset(6)]
public byte byte6;
[FieldOffset(7)]
public byte byte7;
}
The example below produces 2 identical structs:
DoubleStruct ds = new DoubleStruct { value = -36524.063415093093 };
DoubleStruct ds1 = new DoubleStruct
{
byte0 = 0xDD,
byte1 = 0x16,
byte2 = 0x7F,
byte3 = 0x07,
byte4 = 0x82,
byte5 = 0xD5,
byte6 = 0xE1,
byte7 = 0xC0
};
To convert the helper struct to byte array, use:
byte[] bytes = new[] { ds1.byte0, ds1.byte1, ds1.byte2, ds1.byte3,
ds1.byte4, ds1.byte5, ds1.byte6, ds1.byte7 };