c++ - 在 TypeScript 中翻译 c++ 函数

标签 c++ typescript operators bit

给定以下 C++ 编写的函数:

#define getbit(s,i) ((s)[(i)/8] & 0x01<<(i)%8)
#define setbit(s,i) ((s)[(i)/8] |= 0x01<<(i)%8)

如何将它们转换为兼容的 TypeScript 函数?

我想到了:

function setbit(s: string, i: number): number {
    return +s[i / 8] | 0x01 << i % 8;
}

function getbit(s: string, i: number): number {
   return +s[i / 8] & 0x01 << i % 8;
}

我发现 a |= b 等价于 a = a | b,但我不确定 getbit 函数的实现。另外,我真的不明白这些功能应该做什么。有人可以解释一下吗?

谢谢。

编辑:

使用@Thomas 的想法,我最终这样做了:

function setBit(x: number, mask: number) {
    return x | 1 << mask;
}

// not really get, more like a test
function getBit(x: number, mask: number) {
    return ((x >> mask) % 2 !== 0);
}

因为我真的不需要字符串来表示二进制。

最佳答案

字符串在这里不是很好的存储方式。顺便说一句,JS 字符串使用 16 位字符,因此您只使用了可能存储空间的 1/256。

function setbit(string, index) {
    //you could do `index >> 3` but this will/may fail if index > 0xFFFFFFFF
    //well, fail as in produce wrong results, not as in throwing an error.
    var position = Math.floor(index/8), 
        bit = 1 << (index&7),
        char = string.charCodeAt(position);
    return string.substr(0, position) + String.fromCharCode(char|bit) + string.substr(position+1);
}

function getbit(string, index) {
    var position = Math.floor(i/8),
        bit = 1 << (i&7),
        char = string.charCodeAt(position);
    return Boolean(char & bit);
}

更好的是(类型化)数组。

function setBit(array, index){
    var position = Math.floor(index/8),
        bit = 1 << (index&7);
    array[position] |= bit; //JS knows `|=` too
    return array;
}

function getBit(array, index) {
    var position = Math.floor(index/8),
        bit = 1 << (index&7);
    return Boolean(array[position] & bit)
}

var storage = new Uint8Array(100);
setBit(storage, 42);
console.log(storage[5]);

var data = [];
setBit(data, 42);
console.log(data);

两者都适用,但是:

  • 所有类型化数组都有固定长度,在内存分配(创建)后不能更改。

  • 常规数组没有常规类型,例如 8 位/索引左右,限制为 53 位 float ,但出于性能原因,您应该坚持使用最多 INT31(31,而不是 32),这意味着 30 位+ 标志。在这种情况下,JS 引擎可以在幕后稍微优化一下;减少内存影响并且速度更快。

但如果性能是主题,请使用类型化数组!虽然你必须事先知道这个东西能有多大。

关于c++ - 在 TypeScript 中翻译 c++ 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42747826/

相关文章:

c++ - 写 long long 时出现段错误

c++ - 在 Windows x64 上构建 xlnt 库

c++ - 为什么我们不能将 char 分配给字符串?

c++ - string::find() c++ 使用的字符串搜索算法

node.js catch block 在等待时未按预期触发

java - 为什么使用双冒号 (::) 在 Kotlin 中上课?

javascript - 如何根据 JavaScript 中哪个 nodeList 不为空来设置变量?

Angular 2 - typescript 中的 window.print 是什么

typescript - 将 TypeScript 编译为多个目标

c - 运算符 == 在 C 中不起作用