我正在開發基於webgl的渲染器,並且標題中說我需要將4位8位無符號整數打包爲32位浮點型,我寫了 下面的代碼:將4位8位無符號整數轉換爲32位浮點型
//pack 4 8-bit integer to a float
function packIntsToFloat(i1, i2, i3, i4) {
//ensure 32-bit allocation
var ints = new Uint32Array(4);
ints[0] = i1;
ints[1] = i2;
ints[2] = i3;
ints[3] = i4;
ints[0] <<= 24;
ints[1] <<= 16;
ints[2] <<= 8;
ints[3] |= ints[0] | ints[1] | ints[2];
//convert to float
var f = new Float32Array(1);
f[0] = ints[3];
return f[0];
}
//unpack 4 8-bit integer from a float
function unPackIntsFromFloat(f) {
var i = new Uint32Array(4);
i[3] = f;
var mask_7_to_0 = 255;
var mask_15_to_8 = mask_7_to_0 << 8;
var mask_23_to_16 = mask_15_to_8 << 8;
var mask_31_to_24 = mask_23_to_16 << 8;
i[0] = (i[3] & mask_31_to_24) >>> 24;
i[1] = (i[3] & mask_23_to_16) >>> 16;
i[2] = (i[3] & mask_15_to_8) >>> 8;
i[3] = (i[3] & mask_7_to_0);
return new Uint8Array(i);
}
,但它不會,除非跳過工作我需要什麼:
//convert to float
var f = new Float32Array(1);
f[0] = ints[3];
我知道了IEEE標準的,但不應該有位的任何變化,只有他們的解釋纔是價值。 預先感謝您。
非常感謝你!非常非常有幫助,你能解釋一下我寫的代碼嗎? – user2302585 2014-10-02 07:07:56