了解 JavaScript 按位 NOT 运算符和 toString() 函数

发布于 2024-07-29 01:00:10 字数 244 浏览 1 评论 0原文

提前感谢大家:

alert((~1).toString(2));

此输出: -10

但在 PHP/Java 中,它输出 11111111111111111111111111111110

我错过了什么吗? 为什么Javascript要在输出中添加“-”?

Thanks to everyone in advance:

alert((~1).toString(2));

This outputs: -10

But in PHP/Java it outputs 11111111111111111111111111111110

Am I missing something? Why does Javascript add a "-" to the output?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

若能看破又如何 2024-08-05 01:00:10

我知道Java使用二进制补码来表示负数,二进制的11111111111111111111111111111110,即~1给出的,表示-2。 或者,用带有负号的二进制表示,-10,这就是您得到的。

使用二进制补码计算 10 的负数(以 2 为基数)的方法是,首先将所有位取反,得到:

11111111111111111111111111111101

,然后加 1,得到:

11111111111111111111111111111110< /em>

我想同样的情况也发生在 Javascript 中。

I know Java uses two's complement to represent negative numbers, and 11111111111111111111111111111110 in binary, which is what ~1 gives, represents -2. Or, represented in binary with a negative sign, -10, which is what you got.

The way you calculate the negative of 10 (in base 2) using two's complement is that you first invert all of the bits, giving you:

11111111111111111111111111111101

then you add 1, giving you:

11111111111111111111111111111110

I guess the same is happening in Javascript.

风吹短裙飘 2024-08-05 01:00:10

您可以使用移位运算符>>> 在转换为二进制之前将数字转换为无符号整数:

(~1 >>> 0).toString(2) // "11111111111111111111111111111110"

You can use the shift operator >>> to convert the number to an unsigned integer before converting to binary:

(~1 >>> 0).toString(2) // "11111111111111111111111111111110"
凡尘雨 2024-08-05 01:00:10

简短回答:

  1. 按位 NOT (~1) 执行 1 的补码转换
    十进制,给我们 -2
  2. .toString() 函数基本上采用不带符号 2 的十进制,将其转换为二进制 10 并添加一个 - 符号,为我们提供 -10

更详细的答案:

它在函数 .toString()。 当您通过 .toString() 输出数字时:

如果 numObj 为负数,则保留符号。就是这种情况
即使基数是 2; 返回的字符串是正二进制
numObj 的表示形式,前面带有 - 符号,而不是两者的
numObj 的补集。

取自 developer.mozilla.org< /a> 我们得到了这个计算整数的 1 补码的公式,当您对小数执行 NOT (~) 时会使用该公式:

按位记数任何数字 x 都会得到 -(x + 1)。 例如,~5 产量
-6。

也许用这个表和一个例子可以更好地解释:

+-------------------------+-----+-----+-----+-----+-----+-----+------+
| Base 10 Integer         | -3  | -2  | -1  | 0   | 1   | 2   | 3    |
+-------------------------+-----+-----+-----+-----+-----+-----+------+
| Base 10 1's Complement  |  2  |  1  |  0  | -1  | -2  | -3  | -4   |
+-------------------------+-----+-----+-----+-----+-----+-----+------+
| Base 2                  |     |     |     | 0   |  1  |  10 |  11  |
+-------------------------+-----+-----+-----+-----+-----+-----+------+
| Result ~x.toString(2)   | 10  |  1  |  0  | -1  | -10 | -11 | -100 |
+-------------------------+-----+-----+-----+-----+-----+-----+------+
  1. 从基数 10 整数“2”开始,
  2. 基数 10 整数“2”,其 1 的补码是“-3”。 这与执行 NOT (~) 相同
  3. 。toString 函数获取无符号值(= “3”以 10 为基数,=“11”以 2 为基数)
  4. .toString 函数添加一个“-”符号
  5. .toString 输出“-11” ”

Short answer:

  1. A bitwise NOT (~1) performs a 1's complement conversion of the
    decimal which gives us -2
  2. The .toString() function basically takes the decimal without the sign 2, converts it to binary 10 and adds a - sign which gives us -10.

A more detailed answer:

It's in the function .toString(). When you output a number via .toString():

If the numObj is negative, the sign is preserved. This is the case
even if the radix is 2; the string returned is the positive binary
representation of the numObj preceded by a - sign, not the two's
complement of the numObj.

Taken from the developer.mozilla.org we got this formula that calculates the 1's complement of an integer, this is used when you perform a NOT (~) on a decimal:

Bitwise NOTing any number x yields -(x + 1). For example, ~5 yields
-6.

Maybe it's better explained with this table and an example:

+-------------------------+-----+-----+-----+-----+-----+-----+------+
| Base 10 Integer         | -3  | -2  | -1  | 0   | 1   | 2   | 3    |
+-------------------------+-----+-----+-----+-----+-----+-----+------+
| Base 10 1's Complement  |  2  |  1  |  0  | -1  | -2  | -3  | -4   |
+-------------------------+-----+-----+-----+-----+-----+-----+------+
| Base 2                  |     |     |     | 0   |  1  |  10 |  11  |
+-------------------------+-----+-----+-----+-----+-----+-----+------+
| Result ~x.toString(2)   | 10  |  1  |  0  | -1  | -10 | -11 | -100 |
+-------------------------+-----+-----+-----+-----+-----+-----+------+
  1. Starting with Base 10 integer "2"
  2. Base 10 integer "2" its 1's Complement is "-3". This is the same as performing a NOT (~)
  3. .toString function take the unsigned value (= "3" in base 10 and = "11" in base 2)
  4. .toString function adds a "-" symbol
  5. .toString outputs "-11"
清风夜微凉 2024-08-05 01:00:10

这假设您正在使用 32 位...

var valueToNot = parseInt("11110000", 2);
var notResult = 0xFFFFFFFF - valueToNot;
console.log(notResult.toString(2));

结果
11111111111111111111111100001111

This assumes that you are working in 32 bits...

var valueToNot = parseInt("11110000", 2);
var notResult = 0xFFFFFFFF - valueToNot;
console.log(notResult.toString(2));

results in
11111111111111111111111100001111

小ぇ时光︴ 2024-08-05 01:00:10

这是一个在 javascript 中实现 NOT 的解决方案。 它不漂亮,但很有效。


// Since ~ is the two's complement, then the one's complement is ~(num -1).
var num = 9;
num.toString(2);            //returns 1001
~(num - 1).toString(2);    //returns -1001
// WHAT the hell?? I guess the negative sign acts as a sign bit.

如果要查看 NOT(位切换)后的小数的二进制字符串,请使用以下代码。

// Programer: Larry Battle
// Purpose: Provide a bit toggle function for javascript.
var getStrCopy = function (str, copies) {
    var newStr = str;
    copies = (copies > 0) ? copies : 1;
    while (--copies) {
        newStr += str;
    }
    return newStr;
};
var convertDecToBase = function ( dec, base, length, padding ) {
    padding = padding || '0' ;
    var num = dec.toString( base );
    length = length || num.length;
    if (num.length !== length) {
        if (num.length > length) {
            throw new Error("convertDecToBase(): num(" + num + ") > length(" + length + ") too long.");
        }
        num = getStrCopy( padding, (length - num.length)) + num;
    }
    return num;
};
var formatBinaryStr = function( str ){
    return str.replace( /\d{4}/g, '
amp; ' ).replace( /\s$/,'');
};
var toggleBits = function( dec, length, doFormat ){
    length = length || 8;
    var str = convertDecToBase( dec, 2, length || 8 );
    var binaryStr = str.replace( /0/g, 'o' ).replace( /1/g, '0').replace( /o/g, '1' );
    return ( doFormat ) ? formatBinaryStr( binaryStr ) : binaryStr ;
};

// The following requires Firebug or Google Chrome Dev Tools
clear();
console.log( toggleBits( 1 ) );    // returns "11111110"
console.log( toggleBits( 2 ) );    // returns "11111101"
console.log( toggleBits( 50, 16 ) );// returns "1111111111001101"
console.log( toggleBits( 15, 8, true ) );    // returns "1111 0000"
console.log( toggleBits( 520, 16, true ) ); //returns "1111 1101 1111 0111"

Here's a solution to implement NOT in javascript. It ain't pretty but it works.


// Since ~ is the two's complement, then the one's complement is ~(num -1).
var num = 9;
num.toString(2);            //returns 1001
~(num - 1).toString(2);    //returns -1001
// WHAT the hell?? I guess the negative sign acts as a sign bit.

If you want to view the Binary String of a decimal after a NOT (bit Toggle), then use the following code.

// Programer: Larry Battle
// Purpose: Provide a bit toggle function for javascript.
var getStrCopy = function (str, copies) {
    var newStr = str;
    copies = (copies > 0) ? copies : 1;
    while (--copies) {
        newStr += str;
    }
    return newStr;
};
var convertDecToBase = function ( dec, base, length, padding ) {
    padding = padding || '0' ;
    var num = dec.toString( base );
    length = length || num.length;
    if (num.length !== length) {
        if (num.length > length) {
            throw new Error("convertDecToBase(): num(" + num + ") > length(" + length + ") too long.");
        }
        num = getStrCopy( padding, (length - num.length)) + num;
    }
    return num;
};
var formatBinaryStr = function( str ){
    return str.replace( /\d{4}/g, '
 ' ).replace( /\s$/,'');
};
var toggleBits = function( dec, length, doFormat ){
    length = length || 8;
    var str = convertDecToBase( dec, 2, length || 8 );
    var binaryStr = str.replace( /0/g, 'o' ).replace( /1/g, '0').replace( /o/g, '1' );
    return ( doFormat ) ? formatBinaryStr( binaryStr ) : binaryStr ;
};

// The following requires Firebug or Google Chrome Dev Tools
clear();
console.log( toggleBits( 1 ) );    // returns "11111110"
console.log( toggleBits( 2 ) );    // returns "11111101"
console.log( toggleBits( 50, 16 ) );// returns "1111111111001101"
console.log( toggleBits( 15, 8, true ) );    // returns "1111 0000"
console.log( toggleBits( 520, 16, true ) ); //returns "1111 1101 1111 0111"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文