Reputation: 1044
In a web browser we receive binary structs in ArrayBuffers over WebSocket from a C# server that contain 128 bit .NET Decimal types.
We need to convert this to a native JavaScript Number.
How do we do this in JavaScript?
Upvotes: 1
Views: 401
Reputation: 36
function DotNetDecimalToNumber(inputArrayBuffer, isLittleEndian = true){
let dataview = new DataView(inputArrayBuffer);
let scale = dataview.getUint8(2);
let sign = dataview.getUint8(3);
let hi32 = dataview.getUint32(4, isLittleEndian);
let low64 = dataview.getBigUint64(8, isLittleEndian);
let divisor = 1.0;
while (scale-- > 0){
divisor *= 10;
}
if (sign > 0){
divisor *= -1;
}
let highPart = 0.0;
if (hi32 > 0){
highPart = hi32 / divisor;
highPart *= 4294967296.0;
highPart *= 4294967296.0;
} else {
highPart = 0.0;
}
return (Number(low64) / divisor) + highPart;
}
//Clamped number array equivalent of byte output from C# struct for Decimal -720819.587673906
let testNumber = [0, 0, 9, 128, 0, 0, 0, 0, 50, 111, 120, 227, 148, 143, 2, 0];
//Generates a Uint8Array and uses underlying ArrayBuffer, for this example
console.log(DotNetDecimalToNumber(new Uint8Array(testNumber).buffer, true));
//outputs -720819.587673906
This converts approximately 1000 Decimals per millisecond on my machine.
Upvotes: 2