javascript - 如何在javascript中从ArrayBuffer获取Short值?

标签 javascript java

我在java中有一个ByteBuffer,我从中写下前几个值,它们是:

[-112, -37, 96, -28, -16, -28, -64, -25, 112, -30, -112, -29, 48, -28, 48,
 -30, -48, -28, 32, -27, 80, -31, -112, -29, 80, -31, -96, -28, -96, -28, 
 -112, -30, -96, -30, -16, -27, 16, -28, 48, -27, -64, -32, -112, -30, -32,
 -29, etc ,...]

mybuffer.getShort() 这样的代码返回值 -9328、-7072 等...
根据Java API:

short java.nio.ByteBuffer.getShort()

用于读取短值的相对 get 方法。

Reads the next two bytes at this buffer's current position, composing them into a short value according to the current byte order, and then increments the position by two.

Returns:The short value at the buffer's current position

Throws:BufferUnderflowException - If there are fewer than two bytes remaining in this buffer.

到这里一切都很好,所以问题从这里开始,问题是如果我想在 javascript 中实现相同的目标,那么该怎么做?

我在javascript中使用ArrayBuffer,但是根据java API,他们做了一些计算,这非常令人困惑。

这是我的 JavaScript 代码:

var buf = new ArrayBuffer(res.length); // 2 bytes for each char
var bufView = new Uint16Array(buf); //buf is same as buffer in java ByteBuffer above.

for (var i = 0, strLen = res.length; i < strLen; i++) {
    bufView[i] = res.charCodeAt(i);
}

最佳答案

只是需要同样的东西,但很失望没有提供答案:D

玩了一下Scala,然后跳到Java,终于得到了这个 (当然这符合我的需求,Java的实现有不同的选择..)

const getShort = (a,b) => a << 8 | b << 0

如果你有一个 Uint8Array([1,2,3,4,5,6])

const uiArr = new Uint8Array([1,2,3,4,5,6])

并且您想要获得第一个短值,只需传递数组中的前两个值

const firstShort = getShort(uiArr[1], uiArr[0]) // in my case little endian 
const secondShort = getShort(uiArr[3], uiArr[2])

关于javascript - 如何在javascript中从ArrayBuffer获取Short值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31433051/

相关文章:

javascript - 是否有可以显示正在执行的 JS 的 Google Chrome 扩展程序?

javascript - 无法搜索 classList .with contains

javascript - 获取div中的链接文本

java - 在 CodeModel 的 switch 中使用 Enum 常量

java - 如何评估变量

java - 如何使用 Maven 获取项目的所有嵌套依赖项?

javascript - 如何在Chrome打包应用程序中使用Knockout Js进行MVVM?它不允许在 html 中使用内联 JS

php - 使用 PHP 缩小内联 JavaScript

java - HtmlUnitDriver中提供浏览器版本有什么用

java - mockito `when` 未返回正确的模拟列表