Skip to content

Instantly share code, notes, and snippets.

@heroqu
Created August 25, 2017 10:53
Show Gist options
  • Save heroqu/983f8c6c456f82c2f33790bca2921865 to your computer and use it in GitHub Desktop.
Save heroqu/983f8c6c456f82c2f33790bca2921865 to your computer and use it in GitHub Desktop.
function to convert javascript integer to an array of 4 bytes
function int32ToBytes (int) {
return [
int & 0xff,
(int >> 8) & 0xff,
(int >> 16) & 0xff,
(int >> 24) & 0xff
]
}
// 3 (base 10) = 00000000000000000000000000000011 (base 2)
console.log(int32ToBytes(3)) // -> [ 3, 0, 0, 0 ]
// 258 (base 10) = 00000000000000000000000100000010 (base 2)
console.log(int32ToBytes(258)) // -> [ 2, 1, 0, 0 ]
// 2147483647 (base 10) = 01111111111111111111111111111111 (base 2)
console.log(int32ToBytes(2147483647)) // -> [ 255, 255, 255, 127 ]
// -2147483648 (base 10) = 10000000000000000000000000000000 (base 2)
console.log(int32ToBytes(-2147483648)) // -> [ 0, 0, 0, 128 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment