2014-10-01 303 views
2

我正在开发基于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标准的,但不应该有位的任何变化,只有他们的解释才是价值。 预先感谢您。

回答

3

所有TypedArray s为一个类型不可知ArrayBuffer只是意见,所以你可以简单地使用:

包装: new Float32Array((new Uint8Array([i1,i2,i3,i4])).buffer)[0];

开箱: new Uint8Array((new Float32Array([f])).buffer);

查看文档ArrayBufferView欲了解更多信息。

+0

非常感谢你!非常非常有帮助,你能解释一下我写的代码吗? – user2302585 2014-10-02 07:07:56

1

你想要做什么?

例如你是否试图将浮点位置和无符号字节颜色放在同一个缓冲区中?在这种情况下,对同一缓冲区制作2个视图。示例:

var numVerts = 10; 
var bytesPerPosition = 3 * 4; // x,y,z * 4 bytes per float 
var bytesPerColor = 4; // r,g,b,a 1 byte each 
var bytesPerVertex = bytesPerPosition * bytesPerColor; 
var sizeOfBuffer = numVertex * bytesPerVertex; 
var offsetOfPositions = 0; 
var offsetOfColor = bytesPerPosition; 

// now make the buffer. 
var asUint8 = new Uint8Array(sizeOfBuffer); 
var asFloat = new FloatArray(asUint8.buffer); 

您现在有2个视图到同一缓冲区。因此,例如,设置的位置你会切实做好

var strideInFloats = bytesPerVertex/4; 

function setPosition(index, x, y, z) { 
    var offset = strideInFloats * index; 
    asFloat[offset ] = x; 
    asFloat[offset + 1] = y; 
    asFloat[offset + 2] = z; 
} 

要设置颜色将有效

function setColor(index, r, g, b, a) { 
    var offset = strideInBytes * index + offsetToColor; 
    asUint8[offset ] = r; 
    asUint8[offset + 1] = g; 
    asUint8[offset + 2] = b; 
    asUint8[offset + 3] = a; 
} 

当设置的属性,你会做这样的事情

gl.vertexAttribPointer(positionLoc, 3, gl.FLOAT, false, bytesPerVertex, 
         offsetOfPosition); 
gl.vertexAttribPointer(colorLoc, 4, gl.UNSIGNED_BYTE, true, bytesPerVertex, 
         offsetOfColor); 
相关问题