ECMAScript 6否定二进制文字 [英] ECMAScript 6 negative binary literal

查看:76
本文介绍了ECMAScript 6否定二进制文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

借助EMCAScript6,我发现有一种方法可以使用0b0B前缀.我正在尝试使用它,却找不到代表负数的方法(因为它没有使用二进制补码).我想念什么吗?我找不到实际规范中解释二进制文字的地方.

With EMCAScript6, I see there's a way to represent binary literals using the 0b or 0B prefix. I was experimenting with it, and couldn't find a way to represent a negative number (since it's not using two's-complement). Am I missing something? I can't find where binary literals are explained in the actual spec.

我想我可以使用~(num - 1)-num之类的操作自己实现它:

I suppose I could implement it myself with an operation like ~(num - 1) or -num:

function twosComplement(num) {
  return ~(num - 1);
}

var flag = 0b100;

console.log(flag);
console.log(twosComplement(flag));

// is this output normal? I thought binary used a sign bit
console.log(twosComplement(flag).toString(2));

推荐答案

要输入负数,只需在您的文字前加上-符号(一元减运算符)即可

To input negative number just prefix your literal with - sign (unary minus operator):

-0b11010 // -26

有关二进制文字的说明,请参见数字文字.

Specification for binary literals is in section Numeric Literals.

相关片段:

NumericLiteral ::(...)BinaryIntegerLiteral

NumericLiteral :: (...) BinaryIntegerLiteral

BinaryIntegerLiteral :: 0b BinaryDigits

BinaryIntegerLiteral :: 0b BinaryDigits

BinaryDiggits01.

这篇关于ECMAScript 6否定二进制文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆