Javascript Typed Arrays和Endianness [英] Javascript Typed Arrays and Endianness

查看:236
本文介绍了Javascript Typed Arrays和Endianness的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用WebGL渲染二进制编码的网格文件。二进制文件以big-endian格式写出(我可以通过在十六进制编辑器中打开文件或使用fiddler查看网络流量来验证这一点)。当我尝试使用Float32Array或Int32Array读取二进制响应时,二进制文件被解释为little-endian并且我的值是错误的:

I'm using WebGL to render a binary encoded mesh file. The binary file is written out in big-endian format (I can verify this by opening the file in a hex editor, or viewing the network traffic using fiddler). When I try to read the binary response using a Float32Array or Int32Array, the binary is interpreted as little-endian and my values are wrong:

// Interpret first 32bits in buffer as an int
var wrongValue = new Int32Array(binaryArrayBuffer)[0];

我找不到 http://www.khronos.org/registry/typedarray/specs/latest/ 所以我想知道这笔交易是什么?在使用类型化数组读取时,我是否应该假设所有二进制数据都应该是小端?

I can't find any references to the default endianness of typed arrays in http://www.khronos.org/registry/typedarray/specs/latest/ so I'm wondering what's the deal? Should I assume that all binary data should be little-endian when reading using typed arrays?

为了解决这个问题,我可以使用DataView对象(在前面的链接中讨论过) )并调用:

To get around the problem I can use a DataView object (discussed in the previous link) and call:

// Interpret first 32bits in buffer as an int
var correctValue = new DataView(binaryArrayBuffer).getInt32(0);

默认情况下,getInt32等DataView函数读取big-endian值。

The DataView functions such as "getInt32" read big-endian values by default.

(注意:我已经使用谷歌Chrome 15和Firefox 8进行了测试,它们的行为方式相同)

(Note: I've tested using Google Chrome 15 and Firefox 8 and they both behave the same way)

推荐答案

当前的行为,有点可悲的是,字节序是底层硬件的字节序。由于几乎所有台式电脑都是x86,这意味着小端。大多数ARM操作系统都使用小端模式(ARM处理器是双端的,因此可以在任何一种模式下运行)。

The current behaviour, somewhat sadly, is that the endianness is that of the underlying hardware. As almost all desktop computers are x86, this means little-endian. Most ARM OSes use little-endian mode (ARM processors are bi-endian and thus can operate in either).

这有点令人难过的原因是它意味着几乎没有人会测试他们的代码是否适用于大端硬件,损害了什么,以及整个网络平台是围绕代码在整个实现和平台上统一工作而设计的事实,这会破坏。

The reason why this is somewhat sad is the fact that it means almost nobody will test whether their code works on big-endian hardware, hurting what does, and the fact that the entire web platform was designed around code working uniformly across implementations and platforms, which this breaks.

这篇关于Javascript Typed Arrays和Endianness的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆