Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# - byte array improper conversion to MB

The file is about 24mb, and it's held in a DataBase so I convert it to a bit array and then, after multiple suggestions, I use bitconverter.tosingle(,) and this is giving me bad results, here's my code:

     byte[] imgData = prod.ImageData;

     float myFloat = BitConverter.ToSingle(imgData, 0);

     float mb = (myFloat / 1024f) / 1024f;

When I debug, I get these results:

byte[24786273]

myFloat = 12564.0361

mb = 0.0119819986

what is weird is that he size of the array is exactly as the file should be. How do I correctly convert this to float and then so it shows as mb?

EDIT: I tried setting up myFloat as imgData.Length, then the size is correct, however is this a correct way to do it, and can it cause a problem in the future with bigger values?

like image 557
ab1428x Avatar asked Dec 04 '22 08:12

ab1428x


1 Answers

You are taking the first four bytes out of the image and converting it to an IEEE floating point. I'm not an expert on image files so I'm not sure if the first four bytes are always the length, even if this is the case it would still not be correct (see the specification). However the length of the file is already known through the length of the array, so an easier way to get the size is:

byte[] imgData = prod.ImageData;

float mb = (imgData.Length / 1024f) / 1024f;

To address your concerns: this will still work for large files, consider a 24TB example.

var bytes = 24L * 1024 * 1024 * 1024 * 1024;

var inMb = (bytes / 1024.0F / 1024.0F);
like image 129
Bas Avatar answered Jan 12 '23 21:01

Bas