I have a problem to convert an byte array to double array using BitConverter.ToDouble()
.
Simply my program will select an image then convert the image to by
I think you need to back up a bit and explain what you are actually trying to do. Each BitConverter.ToDouble will convert 8 consecutive bytes into 1 double. If you start at the next position in the byte array, you are using 7 bytes that have already been used. Since each conversion will need 8 bytes, you will need to stop at Length - 7.
Anyway, you are going to end up inflating the size of the data by a factor of 8.
I think some explanation of what this is for might help you get some better answers.
class Program { static void Main(string[] args) {
Program p = new Program();
p.Test();
}
private void Test()
{
Image i = Image.FromFile(@"C:\a.jpg");
Bitmap b = new Bitmap(i);
MemoryStream ms = new MemoryStream();
b.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
byte[] by = ms.ToArray();
double[] db = new double[(int)(Math.Ceiling((double)by.Length / 8))];
int startInterval = 1;
int interval = 8;
int k = 0;
byte[] bys = new byte[8];
int n = 1;
for (int m = startInterval; m <= interval && m<=by.Length; m++,n++)
{
bys[n-1] = by[m-1];
if (m == interval)
{
db[k] = BitConverter.ToDouble(bys, 0);
startInterval += 8;
interval += 8;
k++;
n = 0;
Array.Clear(bys, 0, bys.Length);
}
if (m == by.Length)
{
db[k] = BitConverter.ToDouble(bys, 0);
}
}
}
}
BitConverter.ToDouble(byte[], int)
uses eight bytes to construct a 64-bit double, which explains your problem (once you get to the 7th to last element, there are no longer eight bytes left). I'm guessing this is not what you want to do, based on how you set up your loop.
I imagine you want something like:
for(int i = 0; i < index; i++)
{
dImageArray[i] = (double)imageArray[i];
}
Edit - or using LINQ, just for fun:
double[] dImageArray = imageArray.Select(i => (double)i).ToArray();
On the other hand...
If BitConverter
is definitely what you want, then you'll need something like:
double[] dImageArray = new double[imageArray.Length / 8];
for (int i = 0; i < dImageArray.Length; i++)
{
dImageArray[i] = BitConverter.ToDouble(imageArray, i * 8);
}
Again, based on your code, I think the first solution is what you need.