【发布时间】:2019-05-22 01:31:19
【问题描述】:
我从一个 base-64 编码的字符串加载一个字节数组,我想解析它。
但是值以不同的方式编码,我想复制 DataView 的行为。
例子:
function parse(data){
view = new DataView(data.buffer);
return {
headerSize : view.getUint8(0),
numberOfPlanes : view.getUint16(1, true),
width: view.getUint16(3, true),
height: view.getUint16(5, true),
offset: view.getUint16(7, true)
};
}
用法:
data = new Uint8Array([8, 96, 0, 0, 2, 0, 1, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
parse(data)
返回{headerSize: 8, numberOfPlanes: 96, width: 512, height: 256, offset: 8}
稍后我需要使用DataView.getFloat32。
现在我有这样的东西:
def get_bin(a):
ba = bin(a)[2:]
return "0" * (8 - len(ba)) + ba
def getUInt16(arr, ind):
a = arr[ind]
b = arr[ind + 1]
return int(get_bin(b) + get_bin(a), 2)
def getFloat32(arr, ind):
return bin_to_float("".join(get(i) for i in arr[ind : ind + 4][::-1]))
def bin_to_float(binary):
return struct.unpack("!f", struct.pack("!I", int(binary, 2)))[0]
但图书馆可以更高效、更通用
浮动示例:[111, 62, 163, 36] 应该产生 7.079574826789837e-17
【问题讨论】:
标签: javascript python-3.x