Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第十四天:2 进制与 10 进制转换 #16

Open
sofish opened this issue Apr 28, 2016 · 0 comments
Open

第十四天:2 进制与 10 进制转换 #16

sofish opened this issue Apr 28, 2016 · 0 comments
Milestone

Comments

@sofish
Copy link
Owner

sofish commented Apr 28, 2016

呃,这其实是一个很大的话题,虽然说起来只有几句话。拿简单的十进制数字 3,如果转换成二进制:

3..toString(2) // '11'

呃,浏览器里如何显示二进制呢?我们这里忽略,跳出来说一下为什么是 3..toString() 而不是 3.toString(),是不是也曾误了 Number 并没有 toString 方法?用 .. 只是一个 hack 避开了小数点。另外可以写成 (3).toString() 这样就明白多了。转回来。关于如何把二进制转成 10 进制,就更简单了:

parseInt('11', 2) // 3

同样的,可以用带上像 2 8 10 16 这几个参数,来进行 2、8、10、16 进制的转换。不过负数呢?考虑一下这个执行返回什么:

(-3).toString(2) // '-11'

看!起!来!好!像!是!对!的!不过负数通常是以补码来表示的,而什么叫补码?( # )补码形式是指一个数的负对应值( negative counterpart )( 如 5 和 -5 )为数值的所有比特位反转后,再加 1。那么,-3 的值应该是:

(-3 >>> 0).toString(2) // 11111111111111111111111111111101

而关于为什么要用无符号右移 >>> 呢?其实右移了 0 位,( # ) (right logical shift) coerces its arguments to unsigned integers`,然后再转成 2 进制。

再次逼死文科生。我睡觉去了。

@sofish sofish added this to the Daily Post milestone Apr 28, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant