tags:

views:

56

answers:

3

I'm trying to load some decimal values from a file but I can't work out the correct way to take the raw values and convert them into decimals.

I've read the file out into a byte array, and each chunk of four bytes is supposed to represent one decimal value. To help figure it out, I've constructed a table of how the decimal values 1 through to 46 are represented as four byte chunks.

For instance, the number 1 appears as 0,0,128,63 the number 2 as 0,0,0,64 and so on up to 46, which is 0,0,56,66. The full table is available here.

There is also another series of numbers which go to three decimal places and include negatives, which is here.

The only documentation I have states

They are stored least significant byte first: 1's, 256's, 65536's, 16777216's. This makes the hex sequence 01 01 00 00 into the number 257 (decimal). In C/C++, to read e.g. a float, do: float x; fread(&x, sizeof(float), 1, fileptr);

However I'm using .NET's File.ReadAllBytes method so this isn't much help. If anyone can spare a few minutes to look at the examples files and see if they can spot a way to convert the values to decimals I'd be most grateful.

A: 

Have you looked into using the BitConverter class? It converts between byte arrays and various types.

BlueMonkMN
Thanks this is definitely the way to go.
gilles27
+2  A: 

You can use BitConverter.ToSingle to read a float value from a byte array, so to get a sequence of floats, you could do something like this:

byte[] data = File.ReadAllBytes(fileName);
int count = data.Length / 4;
Debug.Assert(data.Length % 4 == 0);

IEnumerable<float> values = Enumerable.Range(0, count)
    .Select(i => BitConverter.ToSingle(data, i*4));
Lee
I've marked this correct as it is slightly more detailed. Thanks very much, wasn't expecting it to be this simple.
gilles27
A: 

As others have mentioned, use the BitConverter class, see the example below:

     byte[] bytez = new byte[] { 0x00, 0x00, 0x80, 0x3F };
     float flt = BitConverter.ToSingle(bytez, 0); // 1.0

     bytez = new byte[] { 0x00, 0x00, 0x00, 0x40 };
     flt = BitConverter.ToSingle(bytez, 0); // 2.0

     bytez = new byte[] { 0, 0, 192, 190 };
     flt = BitConverter.ToSingle(bytez, 0); // -0.375
SwDevMan81