我被要求将整数转换为 32 位二进制数。
因此使用 integer.toString(2)
并以 0 和 1 的 32 位二进制格式获得所需的值。但实际上我被要求做的是将整数转换为 4 个字节的数据。
我无法获得建议的输出。我用过integer.toString(8)
, integer.toString(16)
。但没有用。
例子:
num=1065489844
num.toString(2) //Output: 111111100000100001010110110100
num.toString(8) //Output: 7740412664
请告诉我,我缺少的地方。
最佳答案
现在您可以使用ArrayBuffer
和DataView
。它们是原生的,因此如果您需要经常使用它,性能会好得多。
function toBytesInt32 (num) {
arr = new ArrayBuffer(4); // an Int32 takes 4 bytes
view = new DataView(arr);
view.setUint32(0, num, false); // byteOffset = 0; litteEndian = false
return arr;
}
等于
function toBytesInt32 (num) {
arr = new Uint8Array([
(num & 0xff000000) >> 24,
(num & 0x00ff0000) >> 16,
(num & 0x0000ff00) >> 8,
(num & 0x000000ff)
]);
return arr.buffer;
}
它使用 javascript 按位运算符来实现这一点。
关于javascript - 在javascript中将32位整数转换为4字节数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15761790/