Noitidart Noitidart - 3 months ago 17
Javascript Question

Trying to replicate pythons struct.unpack ">L" in javascript with TypedArrays

I am trying to reproduce the following python in javascript.

import struct
val = struct.unpack(">L", "MACS")[0]


val
is now
1296122707
(same as
0x4d414353
). Trying the same with
htk1
gives
1752460081
same as (
0x68746b31
).

I was trying to bring this to javacript so got to studying and came across this documentation on python - https://docs.python.org/3/library/stdtypes.html#int.from_bytes

So the above is the same as:

int.from_bytes(b"MACS", "big")


However I am not able to port it to javascript. Can you please help me understand this to port, or if its already available out there?

Here was my attempt:

function unpackL(fourCharCode) {
var buf = new ArrayBuffer(8);
var view = new DataView(buf);
view.setUint8(0, String.charCodeAt(fourCharCode[0]), true);
view.setUint8(2, String.charCodeAt(fourCharCode[1]), true);
view.setUint8(4, String.charCodeAt(fourCharCode[2]), true);
view.setUint8(6, String.charCodeAt(fourCharCode[3]), true);
return new Uint32Array(buf);
}


However
unpackL('htk1')
gives me
Uint32Array [ 7602280, 3211371 ]
.

Thanks

Answer

Here's a function that does this (returning undefined if the string is the wrong length):

function stringToUnsignedInt(string) {
  if (string.length !== 4) {
    return undefined;
  }

  return (string.charCodeAt(0) << 24) +
         (string.charCodeAt(1) << 16) +
         (string.charCodeAt(2) << 8) +
         string.charCodeAt(3);
}

console.log(stringToUnsignedInt("MACS") === 1296122707); // true
console.log(stringToUnsignedInt("htk1") === 1752460081); // true
Comments