1

We are receiving a single 32 bit integer value from a server

{
"value": -1072678909
}

In reality they have packed four separate 1 byte values into this one number so we need to read each byte separately to get its value. in this case...

note: reading from right to left

  • The first byte is 00000011 (e.g. value of 3)
  • The second byte is 00111000 (e.g. value of 56)
  • The third byte is 00010000 (e.g. value of 16)
  • The fourth byte is 11000000 (e.g. value of 192)

How can we accomplish this in JavaScript?

0

1 Answer 1

3

Pretty easy using bitshifting and masks:

var byte1 = val & 0xff;
var byte2 = (val>>8) & 0xff;
var byte3 = (val>>16) & 0xff;
var byte4 = (val>>24) & 0xff;
Sign up to request clarification or add additional context in comments.

2 Comments

This works for 32 bit integers, when I try to translate to a 64 bit version I get invalid results. Is there a limit to how much JS can support? (*Ex. with 2251816993685505, expected to read 1 2 4 8. I changed the above to something like (val >> 8) & 0xffff).
Ok, but then your question changes to "how do I extract 4 short (2bytes) values from a 64bit integer", which is somewhat different. Javascript has no 64bit integer and values are stored as double precision floats. Bitshifting over this range is not possible, so you may be better off just bigValue.toString(16) and hacking out the parts with string manipulation.

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.