2

I want to write a buffer into an array and then access that array with the Float64Array view. This seems to be a lot more difficult than it should. I have used the mozilla documentation but still having problems....

I have tried multiple variants of below. Does anyone know why this is not working? At the end I should be able to print out the first float which is 4.

//64 bit floating point numbers with 8 bytes each in hex
//first  float64 bytes : 4 = 0x4010000000000000
//second float64 bytes : 5 = 0x4014000000000000

//2 x 8 bytes in a buffer with each hex number
var buff = new Buffer("40100000000000004014000000000000", "hex");
var ab = new ArrayBuffer(buff.length);
var view = new DataView(ab);

for (var i = 0; i < buff.length; ++i) {
    view[i] = buff[i];
}

console.log(new Float64Array(ab).length);//prints 2
console.log(new Float64Array(ab)[0]);// SHOULD print '4' but prints 0

2 Answers 2

1

Probs due to endianness. Using node Buffer API:

var buff = new Buffer("40100000000000004014000000000000", "hex");
buff.readDoubleLE(0) // 2.0553e-320
buff.readDoubleBE(0) // 4

And if we reverse buff and read from the 8th byte:

var buffRev = new Buffer("00000000000014400000000000001040", "hex")
buff.readDoubleLE(8) // 4
buff.readDoubleBE(8) // 2.0553e-320

Feel free to correct/extend if you know more.

Sign up to request clarification or add additional context in comments.

Comments

0

I ended up realising that really the data needed to be read 'INTO' the view in correct chunks. In the example I provided this means two reads of 8 bytes. With each read needing to be populate one item in the Float64Array. Surprised this is not easier and I can't just populate the ArrayBuffer with the entire underlying buffer.

Anyway this is what I ended up with...

var buff = new Buffer("40100000000000004014000000000000", "hex");
var ab = new ArrayBuffer(buff.length);
var view = new Float64Array(ab);

var viewIndex = 0;
for (var bufferIndex=0;bufferIndex<buff.length;bufferIndex=bufferIndex+8)            {

    view[viewIndex] = buff.readDoubleLE(bufferIndex);
    viewIndex++;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.