I’m trying to convert a large number into an 8 byte array in javascript.
Here is an IMEI that I am passing in: 45035997012373300
var bytes = new Array(7);
for(var k=0;k<8;k++) {
bytes[k] = value & (255);
value = value / 256;
}
This ends up giving the byte array: 48,47,7,44,0,0,160,0. Converted back to a long, the value is 45035997012373296, which is 4 less than the correct value.
Any idea why this is and how I can fix it to serialize into the correct bytes?
Your value and the largest JavaScript integer compared:
JavaScript cannot represent your original value exactly as an integer; that’s why your script breaking it down gives you an inexact representation.
Related:
Edit: If you can express your number as a hexadecimal string:
If you need the bytes ordered from least-to-most significant, throw a
.reverse()on the result.