I was asked to convert the integers to 32-bit binary numbers.
So is used integer.toString(2)
and got the required value in 32-bit binary format of 0\'sand 1\'s. But
SEIAROTg's answer does not output a string. I have theroughly tested with both positive and negative numbers and this code will give you a 4 byte string output representing the number in big endien format(2's compliment 0xFFFFFFFF = -1).
var toBytesInt32=function(num) {
var ascii='';
for (let i=3;i>=0;i--) {
ascii+=String.fromCharCode((num>>(8*i))&255);
}
return ascii;
};
by the way if you want to go the other way around you can use
var fromBytesInt32=function(numString) {
var result=0;
for (let i=3;i>=0;i--) {
result+=numString.charCodeAt(3-i)<<(8*i);
}
return result;
};
to convert a 4 byte string to an integer