javascript - 从 C/C++ 移植到 JavaScript 时如何处理负数或无符号字符?

标签 javascript c++ c casting fromcharcode

我正在尝试将一个旧的 C++ 词法分析器 ( source ) 移植到 JavaScript,但我对 C/C++ 的不理解有点挣扎。

我有一个参数 c,正如我目前所见,它可以是我正在解析的输入文件 block 上的位置索引 (*yy_cp ) 或存储在此地址的实际(包括 nul)字符。我需要使用 c 作为查找表中的索引。词法分析器这样做:

/* Promotes a possibly negative, possibly signed char to an
 * unsigned integer for use as an array index.  If the signed char
 * is negative, we want to instead treat it as an 8-bit unsigned
 * char, hence the double cast.
 */
#define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c)

并这样调用它:

register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)];

它将在 yy_c 中存储查找表 yy_ec 的值,其中包含 256 个条目(我假设是扩展 ASCII)。要查找的位置由 YY_SC_TO_UI 生成,这就是我将其移植到 JavaScript 的地方。 YY_SC_TO_UI 必须返回一个介于 0-255 之间的数字,所以我只使用我拥有的,然后:

 "[c]".charCodeAt(0)

或者在 JS 中处理“possible negative, possible signed char”还有什么我需要注意的吗?

谢谢。

最佳答案

根据编译器的不同,char 可以是signedunsigned。据推测,作者希望它以相同的方式工作,并确保在从 char 转换为 unsigned int 时,值始终为零扩展,而不是符号扩展。确保值为 0..255 而不是 -128..127 的安全方法。

According to MDN, range of return value of charCodeAt is larger:

The charCodeAt() method returns an integer between 0 and 65535...

这取决于您的输入,您希望如何处理超出范围的可能值,但一种替代方法可能是简单的位屏蔽:

"€".charCodeAt(0) & 0xff;

关于javascript - 从 C/C++ 移植到 JavaScript 时如何处理负数或无符号字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43846500/

相关文章:

javascript - 在 Parse 中检索字符串

c++ - STL 中的迭代器指针如何工作

c++ - '支架初始化'。 (C++)

c - 为什么 _do_fork() 的 kretprobe 只返回一次?

c - 如何正确释放指针

c - 已经释放内存

javascript - 类中的对象设置为变量

javascript - 计算像 "loop "这样的数字

javascript - 在 JavaScript 中为动态生成的复选框触发警报消息时出现问题

c++ - dll文件是否可以初始化-A Dll constructor