我正在尝试将一个旧的 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
可以是signed
或unsigned
。据推测,作者希望它以相同的方式工作,并确保在从 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/