Sometimes, we want to convert a 32 bit integer into 4 bytes of data in JavaScript.
In this article, we’ll look at how to convert a 32 bit integer into 4 bytes of data in JavaScript.
How to convert a 32 bit integer into 4 bytes of data in JavaScript?
To convert a 32 bit integer into 4 bytes of data in JavaScript, we can use the ArrayBuffer
and DataView
constructors.
For instance, we write:
const toBytesInt32 = (num) => {
const arr = new ArrayBuffer(4);
const view = new DataView(arr);
view.setUint32(0, num, false);
return arr;
}
console.log(toBytesInt32((57586868).toString(2)))
to define the toBytesInt32
function that takes the num
string.
In it, we create an ArrayBuffer
with 4 to create a 4 bytes array buffer.
Then create a DataView
instance with the array buffer.
And then we populate the view
with num
.
Conclusion
To convert a 32 bit integer into 4 bytes of data in JavaScript, we can use the ArrayBuffer
and DataView
constructors.