You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求与CFSwapInt16LittleToHost等效的JavaScript函数及用法

等效CFSwapInt16LittleToHost的JavaScript实现及用法

Objective-C中的CFSwapInt16LittleToHost核心逻辑是将小端字节序的16位整数转换为主机字节序:如果当前主机是小端字节序,直接返回原数;如果是大端,则交换高低字节。

JavaScript没有内置的直接对应函数,但可以通过DataView(React Native完全支持)简洁实现等效逻辑,也可以手动判断字节序完成转换。

推荐实现:用DataView处理(简洁可靠)

DataView支持指定字节序读写二进制数据,直接利用它的特性就能完成小端到主机字节序的转换:

// 等效CFSwapInt16LittleToHost的函数
function cfSwapInt16LittleToHost(littleEndianUint16) {
    const buffer = new ArrayBuffer(2);
    const view = new DataView(buffer);
    // 按小端字节序写入16位整数
    view.setUint16(0, littleEndianUint16, true);
    // 按主机字节序读取,自动完成转换
    return view.getUint16(0);
}

对应原Objective-C代码的React Native版本

假设reportData是Uint8Array类型(对应OC中的二进制数据),转换后的代码如下:

if (characteristic.uuid === respCharUUID) {
    let rpm = 0;
    if ((reportData[0] & 0x01) === 0) {
        rpm = reportData[1];
    } else {
        // 方式1:用上面的转换函数
        const littleEndianValue = (reportData[2] << 8) | reportData[1];
        rpm = cfSwapInt16LittleToHost(littleEndianValue);
        
        // 方式2:直接用DataView读取(更高效,无需额外函数)
        // const view = new DataView(reportData.buffer, reportData.byteOffset + 1, 2);
        // rpm = view.getUint16(0, true); // 直接按小端读取,自动转主机字节序
    }
    // 这里处理得到的rpm值
}

手动实现逻辑(用于理解原理)

如果需要手动判断主机字节序并交换字节,可以用以下代码:

// 判断主机是否为小端字节序
function isLittleEndian() {
    const buffer = new ArrayBuffer(2);
    new DataView(buffer).setUint16(0, 0x0102, true);
    return new Uint16Array(buffer)[0] === 0x0102;
}

// 交换16位整数的高低字节
function swapUint16(value) {
    return ((value & 0xFF) << 8) | ((value >> 8) & 0xFF);
}

// 手动实现等效函数
function cfSwapInt16LittleToHostManual(littleEndianUint16) {
    return isLittleEndian() ? littleEndianUint16 : swapUint16(littleEndianUint16);
}

这种方式原理清晰,但不如DataView方案简洁,推荐优先使用前者。

内容的提问来源于stack exchange,提问作者Shawn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 09:55:21