Signed and Unsigned Numbers
http://www.electronics.dit.ie/staff/tscarff/signed_numbers/signed_numbers.htm
http://stackoverflow.com/questions/9939760/how-do-i-convert-an-integer-to-binary-in-javascript
http://stackoverflow.com/questions/16155592/negative-numbers-to-binary-string-in-javascript
http://stackoverflow.com/questions/9939760/how-do-i-convert-an-integer-to-binary-in-javascript
http://stackoverflow.com/questions/16155592/negative-numbers-to-binary-string-in-javascript
3
Short answer:
- The
toString()
function basically takes the decimal, converts it to binary and adds a "-" sign. - A zero fill right shift converts it's operand to a 32 signed bit integer in two complements format.
A more detailed answer:
Question 1:
//If you try
(-3).toString(2); //show "-11"
It's in the function
.toString()
. When you output a number via .toString()
:SyntaxnumObj.toString([radix])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.
So basically it takes the decimal, converts it to binary and adds a "-" sign.
- Base 10 "3" converted to base 2 is "11"
- Add a sign gives us "-11"
Question 2:
// but if you fake a bit shift operation it works as expected
(-3 >>> 0).toString(2); // print "11111111111111111111111111111101"
A zero fill right shift converts it's operand to a 32 signed bit integer.
The operands of all bitwise operators are converted to signed 32-bit integers in two's complement format.
add a comment
An 8 bit number system can be used to create 256 combinations (from 0 to 255), and the first 128 combinations (0 to 127) represent positive numbers and next 128 combinations (128 to 255) represent negative numbers.
unsigned 0~256
singed 0 ~ +127 & -1 ~ -128
> -3>>>0
4294967293
>
shift的功能在於往右移並在前面補零
而>>>後面代表的是要移多少格
這邊-3移了零格但作為singed的符號1卻被轉為數字1,意義上有所不同
放在二進位中 -3 跟 4294967293 兩者是相等的
順帶一提要得到 -3 也可以用二補數的方式
以八位元為例
0000 0011 (3)
將3的二進位反相得到3的補數
1111 1100
三的補數再加一得到二補數 (規則是加上補數-1,可複習singed number系統)
1111 1101 (-3)
順帶一提要得到 -3 也可以用二補數的方式
以八位元為例
0000 0011 (3)
將3的二進位反相得到3的補數
1111 1100
三的補數再加一得到二補數 (規則是加上補數-1,可複習singed number系統)
1111 1101 (-3)
留言
張貼留言