JoeGeeky
JoeGeeky

Reputation: 3796

Reading select bytes in numeric values

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

How can we accomplish this in JavaScript?

Upvotes: 1

Views: 48

Answers (1)

spender
spender

Reputation: 120528

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;

Upvotes: 3

Related Questions