If I have an Uint8Array
array in JavaScript, how would I get the last four bytes and then convert that to an int? Using C# I would do something like this:
int count = BitConverter.ToInt32(array, array.Length - 4);
Is there an inequivalent way to do this using JavaScript?
Do you have an example? I think this would do it:
Access the underlying
ArrayBuffer
and create a newTypedArray
with a slice of its bytes:If the
TypedArray
does not cover the entire buffer, you need to be a little trickier, but not much:This works in both cases.
If the bytes you want fit in the alignment boundary of your underlying buffer for the datatype (e.g., you want the 32-bit value of bytes 4-8 of the underlying buffer), you can avoid copying the bytes with
slice()
and just supply a byteoffset to the view constructor, as in @Bergi's answer.Below is a very-lightly-tested function that should get the scalar value of any offset you want. It will avoid copying if possible.
You would use it like this:
It's a shame there are not build in ways to do this. I needed to read variables of variable sizes so based on Imortenson answer I've wrote this little function where
p
is read position ands
is number of bytes to read:It should be more efficient to just create an
Uint32Array
view on the same ArrayBuffer and accessing the 32-bit number directly:Nowadays if you can live with IE 11+ / Chrome 49+ / Firefox 50+, then you can use DataView to make your life almost as easy as in C#:
Test it here: https://jsfiddle.net/3udtek18/1/
A little inelegant, but if you can do it manually based on the endianess.
Little endian:
Big endian:
This can be extended to other data lengths
Edit: Thanks to David for pointing out my typos