ECMAScript 6 negative binary literal

2020-04-20 17:20发布

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.

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));

1条回答
等我变得足够好
2楼-- · 2020-04-20 17:38

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

-0b11010 // -26

Specification for binary literals is in section Numeric Literals.

Relevant fragment:

NumericLiteral :: (...) BinaryIntegerLiteral

BinaryIntegerLiteral :: 0b BinaryDigits

And BinaryDiggits are 0 and 1.

查看更多
登录 后发表回答