Created
August 25, 2017 10:53
-
-
Save heroqu/983f8c6c456f82c2f33790bca2921865 to your computer and use it in GitHub Desktop.
function to convert javascript integer to an array of 4 bytes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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