I need to replicate my hashing algorithm in JavaScript that i have in C#. It requires that i convert a double to a byte array but i can't seem to figure out how the c# method BitConvert.GetBytes() is producing its data. I put in the number 448502400.0 and it outputs 0,0,0,128,154,187,186,65 aka (0x809ABBBA41). If i turn the number to a long before i run it through getBytes() it produces the correct result. 128,154,187,26,0,0,0
How would i go about turning that number (448502400) into a byte[] containing 0x809ABBBA41 in JavaScript where numbers aren't stored the same way?
Just for reference it is NOT possible to change the C# code anymore.
EDIT: Here are the two methods (shamelessly stolen from other questions) to turn a number into bytes. But this generates the long represenation and not the double representation i'm after.
var timestampBytes = [0,0,0,0,0,0,0,0];
var i = 8;
do {
timestampBytes[--i] = timestamp & (255);
timestamp = timestamp >> 8;
} while (i)
And this one
function numberToByte(/*long*/long) {
// we want to represent the input as a 8-bytes array
var byteArray = [0, 0, 0, 0, 0, 0, 0, 0];
for (var index = 0; index < byteArray.length; index++) {
var byte = long & 0xff;
byteArray[index] = byte;
long = (long - byte) / 256;
}
return byteArray;
}
EDIT: My question has been answered in a round about way in the attached answer.
This is my working code which will generate a byte[] which formats to the same byte[] as BitConvert.GetBytes(double)
var bytes = [];
var view = new DataView(new ArrayBuffer(8));
view.setFloat64(0, numberToTurnToDouble);
bytes = bytes.concat(numberToByteArray(view.getUint32(4))); // The second half of the new number
bytes = bytes.concat(numberToByteArray(view.getUint32(0))); // The first half of the number
// Converts an int32 number to its byte array representation
function numberToByteArray(int32) {
var byteArray = [0, 0, 0, 0];
for (var index = 0; index < byteArray.length; index++) {
var byte = int32 & 0xff;
byteArray[index] = byte;
int32 = (int32 - byte) / 256;
}
return byteArray;
}