I’d like to see integers, positive or negative, in binary.
我想看到整数,正的或负的,在二进制中。
Rather like this question, but for JavaScript.
就像这个问题,但是对于JavaScript。
9 个解决方案
#1
9
This answer attempts to address integers with absolute values between Number.MAX_SAFE_INTEGER
(or 2**53-1
) and 2**31
. The current solutions only address signed integers within 32 bits, but this solution will output in 64-bit two's complement form using float64ToInt64Binary()
:
这个答案试图用数字之间的绝对值来处理整数。MAX_SAFE_INTEGER(或2**53-1)和2**31。目前的解决方案只在32位以内的地址有符号整数,但是这个解决方案将使用float64ToInt64Binary()以64位2的补码形式输出:
// IIFE to scope internal variables
var float64ToInt64Binary = (function () {
// create union
var flt64 = new Float64Array(1)
var uint16 = new Uint16Array(flt64.buffer)
// 2**53-1
var MAX_SAFE = 9007199254740991
// 2**31
var MAX_INT32 = 2147483648
function uint16ToBinary() {
var bin64 = ''
// generate padded binary string a word at a time
for (var word = 0; word < 4; word++) {
bin64 = uint16[word].toString(2).padStart(16, 0) + bin64
}
return bin64
}
return function float64ToInt64Binary(number) {
// NaN would pass through Math.abs(number) > MAX_SAFE
if (!(Math.abs(number) <= MAX_SAFE)) {
throw new RangeError('Absolute value must be less than 2**53')
}
var sign = number < 0 ? 1 : 0
// shortcut using other answer for sufficiently small range
if (Math.abs(number) <= MAX_INT32) {
return (number >>> 0).toString(2).padStart(64, sign)
}
// little endian byte ordering
flt64[0] = number
// subtract bias from exponent bits
var exponent = ((uint16[3] & 0x7FF0) >> 4) - 1023
// encode implicit leading bit of mantissa
uint16[3] |= 0x10
// clear exponent and sign bit
uint16[3] &= 0x1F
// check sign bit
if (sign === 1) {
// apply two's complement
uint16[0] ^= 0xFFFF
uint16[1] ^= 0xFFFF
uint16[2] ^= 0xFFFF
uint16[3] ^= 0xFFFF
// propagate carry bit
for (var word = 0; word < 3 && uint16[word] === 0xFFFF; word++) {
// apply integer overflow
uint16[word] = 0
}
// complete increment
uint16[word]++
}
// only keep integer part of mantissa
var bin64 = uint16ToBinary().substr(11, Math.max(exponent, 0))
// sign-extend binary string
return bin64.padStart(64, sign)
}
})()
console.log('8')
console.log(float64ToInt64Binary(8))
console.log('-8')
console.log(float64ToInt64Binary(-8))
console.log('2**33-1')
console.log(float64ToInt64Binary(2**33-1))
console.log('-(2**33-1)')
console.log(float64ToInt64Binary(-(2**33-1)))
console.log('2**53-1')
console.log(float64ToInt64Binary(2**53-1))
console.log('-(2**53-1)')
console.log(float64ToInt64Binary(-(2**53-1)))
console.log('2**52')
console.log(float64ToInt64Binary(2**52))
console.log('-(2**52)')
console.log(float64ToInt64Binary(-(2**52)))
.as-console-wrapper {
max-height: 100% !important;
}
This answer heavily deals with the IEEE-754 Double-precision floating-point format, illustrated here:
这个答案主要涉及IEEE-754双精度浮点格式,如下所示:
seee eeee eeee ffff ffff ffff ffff ffff ffff ffff ffff ffff ffff ffff ffff ffff
---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
[ uint16[3] ] [ uint16[2] ] [ uint16[1] ] [ uint16[0] ]
[ flt64[0] ]
little endian byte ordering
s = sign = uint16[3] >> 15
e = exponent = (uint16[3] & 0x7FF) >> 4
f = fraction
The way the solution works is it creates a union between a 64-bit floating point number and an unsigned 16-bit integer array in little endian byte ordering. After validating the integer input range, it casts the input to a double precision floating point number on the buffer, and then uses the union to gain bit access to the value and calculate the binary string based on the unbiased binary exponent and fraction bits.
解决方案的工作方式是在小端字节排序中创建一个64位浮点数和无符号16位整数数组之间的联合。在验证整数输入范围后,将输入转换为缓冲区上的双精度浮点数,然后使用union访问该值并基于无偏二进制指数和分数位计算二进制字符串。
The solution is implemented in pure ECMAScript 5 except for the use of String#padStart()
, which has an available polyfill here.
解决方案是在纯ECMAScript 5中实现的,除了使用了字符串#padStart(),它在这里有一个可用的polyfill。
#2
312
Answer:
答:
function dec2bin(dec){
return (dec >>> 0).toString(2);
}
dec2bin(1); // 1
dec2bin(-1); // 11111111111111111111111111111111
dec2bin(256); // 100000000
dec2bin(-256); // 11111111111111111111111100000000
You can use Number.toString(2)
function, but it has some problems when representing negative numbers. For example, (-1).toString(2)
output is "-1"
.
可以使用Number.toString(2)函数,但表示负数时存在一些问题。例如,(-1). tostring(2)输出是“-1”。
To fix this issue, you can use the unsigned right shift bitwise operator (>>>
) to coerce your number to an unsigned integer.
为了解决这个问题,您可以使用无符号右移位位操作符(>>>)将您的数字强制为无符号整数。
If you run (-1 >>> 0).toString(2)
you will shift your number 0 bits to the right, which doesn't change the number itself but it will be represented as an unsigned integer. The code above will output "11111111111111111111111111111111"
correctly.
如果你运行(-1 >>> 0). tostring(2)你将把你的数字0位移到右边,这不会改变数字本身,但它将被表示为一个无符号整数。上面的代码将正确地输出“111111111111111111111111111111111111111111111111111111111111”。
This question has further explanation.
这个问题有进一步的解释。
-3 >>> 0
(right logical shift) coerces its arguments to unsigned integers, which is why you get the 32-bit two's complement representation of -3.-3 >>> 0(右逻辑移位)强制它的参数为无符号整数,这就是为什么你得到32位2的-3的补表示。
Note 1: this answer expects a Number as argument, so convert your accordingly.
注意1:这个答案需要一个数字作为参数,所以相应地转换你的。
Note 2: the result is the a string without leading zeros, so zero pad accordingly.
注意2:结果是一个没有前导0的字符串,因此0填充。
#3
153
Try
试一试
num.toString(2);
The 2 is the radix and can be any base between 2 and 36
2是基数,可以是2到36之间的任何底数
source here
源在这里
UPDATE:
更新:
This will only work for positive numbers, Javascript represents negative binary integers in two's-complement notation. I made this little function which should do the trick, I haven't tested it out properly:
这只适用于正数,Javascript用二补符号表示负二进制整数。我做了一个小函数,这个函数应该很有用,我还没有对它进行正确的测试:
function dec2Bin(dec)
{
if(dec >= 0) {
return dec.toString(2);
}
else {
/* Here you could represent the number in 2s compliment but this is not what
JS uses as its not sure how many bits are in your number range. There are
some suggestions https://*.com/questions/10936600/javascript-decimal-to-binary-64-bit
*/
return (~dec).toString(2);
}
}
I had some help from here
我从这里得到了一些帮助
#4
38
The binary in 'convert to binary' can refer to three main things. The positional number system, the binary representation in memory or 32bit bitstrings. (for 64bit bitstrings see Patrick Roberts' answer)
二进制在“转换成二进制”可以指三个主要的东西。位置数字系统、内存中的二进制表示或32位位位字符串。(关于64位比特串,请参阅帕特里克·罗伯茨的回答)
1. Number System
1。数字系统
(123456).toString(2)
will convert numbers to the base 2 positional numeral system. In this system negative numbers are written with minus signs just like in decimal.
(123456). tostring(2)将会将数字转换为基本的2位置数字系统。在这个系统中负数是用负号写的,就像小数一样。
2. Internal Representation
2。内部表示
The internal representation of numbers is 64 bit floating point and some limitations are discussed in this answer. There is no easy way to create a bit-string representation of this in javascript nor access specific bits.
数字的内部表示是64位浮点数,在这个答案中讨论了一些限制。在javascript中创建位字符串表示形式或访问特定位是不容易的。
3. Masks & Bitwise Operators
3所示。面具&按位运算符
MDN has a good overview of how bitwise operators work. Importantly:
MDN很好地概述了位运算符的工作方式。重要的是:
Bitwise operators treat their operands as a sequence of 32 bits (zeros and ones)
位运算符将其操作数视为32位(0和1)的序列
Before operations are applied the 64 bit floating points numbers are cast to 32 bit signed integers. After they are converted back.
在应用操作之前,将64位浮点数转换为32位有符号整数。在他们皈依之后。
Here is the MDN example code for converting numbers into 32-bit strings.
这里是将数字转换为32位字符串的MDN示例代码。
function createBinaryString (nMask) {
// nMask must be between -2147483648 and 2147483647
for (var nFlag = 0, nShifted = nMask, sMask = ""; nFlag < 32;
nFlag++, sMask += String(nShifted >>> 31), nShifted <<= 1);
return sMask;
}
createBinaryString(0) //-> "00000000000000000000000000000000"
createBinaryString(123) //-> "00000000000000000000000001111011"
createBinaryString(-1) //-> "11111111111111111111111111111111"
createBinaryString(-1123456) //-> "11111111111011101101101110000000"
createBinaryString(0x7fffffff) //-> "01111111111111111111111111111111"
#5
34
A simple way is just...
简单的方法就是……
Number(42).toString(2);
// "101010"
#6
8
Note- the basic (x>>>0).toString(2);
has a slight issue when x is positive. I have some example code at the end of my answer that corrects that problem with the >>> method while still using >>>.
注:基本(x > > > 0).toString(2);当x是正的时候有一个小问题。在我的答案后面有一些示例代码,它纠正了>>>方法的问题,但仍然使用>>>。
(-3>>>0).toString(2);
prints -3 in 2s complement.
1111111111101
A working example
一个工作示例
C:\>type n1.js
console.log( (-3 >>> 0).toString(2) );
C:\>
C:\>node n1.js
11111111111111111111111111111101
C:\>
This in the URL bar is another quick proof
这个在URL栏中是另一个快速证明。
javascript:alert((-3>>>0).toString(2))
Note- The result is very slightly flawed, in that it always starts with a 1, which for negative numbers is fine. For positive numbers you should prepend a 0 to the beginning so that the result is really 2s complement. So (8>>>0).toString(2)
produces 1000 which isn't really 8 in 2s complement, but prepending that 0, making it 01000, is correct 8 in 2s complement. In proper 2s complement, any bit string starting with 0 is >=0, and any bit string starting with 1, is negative.
注意——结果是有一点点瑕疵的,因为它总是以1开头,这对于负数是可以的。对于正数,你应该把0放在前面,这样结果就是2s的补码。所以(8>>>0)。tostring(2)生成的不是2s轨道的8,而是在0之前,得到的01000,是2s轨道的8。在固有的2s补码中,任何以0开头的位串都是>=0,而任何以1开头的位串都是负的。
e.g. this gets round that problem
这解决了那个问题
// or x=-5 whatever number you want to view in binary
x=5;
if(x>0) prepend="0"; else prepend="";
alert(prepend+((x>>>0)).toString(2));
The other solutions are the one from Annan(though Annan's explanations and definitions are full of errors, he has code that produces the right output), and the solution from Patrick.
其他的解决方案来自安南(尽管安南的解释和定义充满了错误,他的代码产生了正确的输出),以及帕特里克的解决方案。
Anybody that doesn't understand the fact of positive numbers starting with 0 and negative numbers with 1, in 2s complement, could check this SO QnA on 2s complement. What is “2's Complement”?
任何不理解0开头的正数和1开头的负数的人,在2s轨道中,都可以检查这个所以QnA在2s轨道上。“2的补”是什么?
#7
6
You can write your own function that returns an array of bits. Example how to convert number to bits
您可以编写自己的函数来返回一个位数组。示例如何将数字转换为位
Divisor| Dividend| bits/remainder
2 | 9 | 1
2 | 4 | 0
2 | 2 | 0
~ | 1 |~
example of above line: 2 * 4 = 8 and remainder is 1 so 9 = 1 0 0 1
上面一行的例子:2 * 4 = 8,余数为1,所以9 = 1 0 0 1
function numToBit(num){
var number = num
var result = []
while(number >= 1 ){
result.unshift(Math.floor(number%2))
number = number/2
}
return result
}
Read remainders from bottom to top. Digit 1 in the middle to top.
从下到上读出余数。从中间到上面的数字1。
#8
-2
This is my code:
这是我的代码:
var x = prompt("enter number", "7");
var i = 0;
var binaryvar = " ";
function add(n) {
if (n == 0) {
binaryvar = "0" + binaryvar;
}
else {
binaryvar = "1" + binaryvar;
}
}
function binary() {
while (i < 1) {
if (x == 1) {
add(1);
document.write(binaryvar);
break;
}
else {
if (x % 2 == 0) {
x = x / 2;
add(0);
}
else {
x = (x - 1) / 2;
add(1);
}
}
}
}
binary();
#9
-2
This is the solution . Its quite simple as a matter of fact
这就是答案。其实很简单
function binaries(num1){
var str = num1.toString(2)
return(console.log('The binary form of ' + num1 + ' is: ' + str))
}
binaries(3
)
/*
According to MDN, Number.prototype.toString() overrides
Object.prototype.toString() with the useful distinction that you can
pass in a single integer argument. This argument is an optional radix,
numbers 2 to 36 allowed.So in the example above, we’re passing in 2 to
get a string representation of the binary for the base 10 number 100,
i.e. 1100100.
*/
#1
9
This answer attempts to address integers with absolute values between Number.MAX_SAFE_INTEGER
(or 2**53-1
) and 2**31
. The current solutions only address signed integers within 32 bits, but this solution will output in 64-bit two's complement form using float64ToInt64Binary()
:
这个答案试图用数字之间的绝对值来处理整数。MAX_SAFE_INTEGER(或2**53-1)和2**31。目前的解决方案只在32位以内的地址有符号整数,但是这个解决方案将使用float64ToInt64Binary()以64位2的补码形式输出:
// IIFE to scope internal variables
var float64ToInt64Binary = (function () {
// create union
var flt64 = new Float64Array(1)
var uint16 = new Uint16Array(flt64.buffer)
// 2**53-1
var MAX_SAFE = 9007199254740991
// 2**31
var MAX_INT32 = 2147483648
function uint16ToBinary() {
var bin64 = ''
// generate padded binary string a word at a time
for (var word = 0; word < 4; word++) {
bin64 = uint16[word].toString(2).padStart(16, 0) + bin64
}
return bin64
}
return function float64ToInt64Binary(number) {
// NaN would pass through Math.abs(number) > MAX_SAFE
if (!(Math.abs(number) <= MAX_SAFE)) {
throw new RangeError('Absolute value must be less than 2**53')
}
var sign = number < 0 ? 1 : 0
// shortcut using other answer for sufficiently small range
if (Math.abs(number) <= MAX_INT32) {
return (number >>> 0).toString(2).padStart(64, sign)
}
// little endian byte ordering
flt64[0] = number
// subtract bias from exponent bits
var exponent = ((uint16[3] & 0x7FF0) >> 4) - 1023
// encode implicit leading bit of mantissa
uint16[3] |= 0x10
// clear exponent and sign bit
uint16[3] &= 0x1F
// check sign bit
if (sign === 1) {
// apply two's complement
uint16[0] ^= 0xFFFF
uint16[1] ^= 0xFFFF
uint16[2] ^= 0xFFFF
uint16[3] ^= 0xFFFF
// propagate carry bit
for (var word = 0; word < 3 && uint16[word] === 0xFFFF; word++) {
// apply integer overflow
uint16[word] = 0
}
// complete increment
uint16[word]++
}
// only keep integer part of mantissa
var bin64 = uint16ToBinary().substr(11, Math.max(exponent, 0))
// sign-extend binary string
return bin64.padStart(64, sign)
}
})()
console.log('8')
console.log(float64ToInt64Binary(8))
console.log('-8')
console.log(float64ToInt64Binary(-8))
console.log('2**33-1')
console.log(float64ToInt64Binary(2**33-1))
console.log('-(2**33-1)')
console.log(float64ToInt64Binary(-(2**33-1)))
console.log('2**53-1')
console.log(float64ToInt64Binary(2**53-1))
console.log('-(2**53-1)')
console.log(float64ToInt64Binary(-(2**53-1)))
console.log('2**52')
console.log(float64ToInt64Binary(2**52))
console.log('-(2**52)')
console.log(float64ToInt64Binary(-(2**52)))
.as-console-wrapper {
max-height: 100% !important;
}
This answer heavily deals with the IEEE-754 Double-precision floating-point format, illustrated here:
这个答案主要涉及IEEE-754双精度浮点格式,如下所示:
seee eeee eeee ffff ffff ffff ffff ffff ffff ffff ffff ffff ffff ffff ffff ffff
---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
[ uint16[3] ] [ uint16[2] ] [ uint16[1] ] [ uint16[0] ]
[ flt64[0] ]
little endian byte ordering
s = sign = uint16[3] >> 15
e = exponent = (uint16[3] & 0x7FF) >> 4
f = fraction
The way the solution works is it creates a union between a 64-bit floating point number and an unsigned 16-bit integer array in little endian byte ordering. After validating the integer input range, it casts the input to a double precision floating point number on the buffer, and then uses the union to gain bit access to the value and calculate the binary string based on the unbiased binary exponent and fraction bits.
解决方案的工作方式是在小端字节排序中创建一个64位浮点数和无符号16位整数数组之间的联合。在验证整数输入范围后,将输入转换为缓冲区上的双精度浮点数,然后使用union访问该值并基于无偏二进制指数和分数位计算二进制字符串。
The solution is implemented in pure ECMAScript 5 except for the use of String#padStart()
, which has an available polyfill here.
解决方案是在纯ECMAScript 5中实现的,除了使用了字符串#padStart(),它在这里有一个可用的polyfill。
#2
312
Answer:
答:
function dec2bin(dec){
return (dec >>> 0).toString(2);
}
dec2bin(1); // 1
dec2bin(-1); // 11111111111111111111111111111111
dec2bin(256); // 100000000
dec2bin(-256); // 11111111111111111111111100000000
You can use Number.toString(2)
function, but it has some problems when representing negative numbers. For example, (-1).toString(2)
output is "-1"
.
可以使用Number.toString(2)函数,但表示负数时存在一些问题。例如,(-1). tostring(2)输出是“-1”。
To fix this issue, you can use the unsigned right shift bitwise operator (>>>
) to coerce your number to an unsigned integer.
为了解决这个问题,您可以使用无符号右移位位操作符(>>>)将您的数字强制为无符号整数。
If you run (-1 >>> 0).toString(2)
you will shift your number 0 bits to the right, which doesn't change the number itself but it will be represented as an unsigned integer. The code above will output "11111111111111111111111111111111"
correctly.
如果你运行(-1 >>> 0). tostring(2)你将把你的数字0位移到右边,这不会改变数字本身,但它将被表示为一个无符号整数。上面的代码将正确地输出“111111111111111111111111111111111111111111111111111111111111”。
This question has further explanation.
这个问题有进一步的解释。
-3 >>> 0
(right logical shift) coerces its arguments to unsigned integers, which is why you get the 32-bit two's complement representation of -3.-3 >>> 0(右逻辑移位)强制它的参数为无符号整数,这就是为什么你得到32位2的-3的补表示。
Note 1: this answer expects a Number as argument, so convert your accordingly.
注意1:这个答案需要一个数字作为参数,所以相应地转换你的。
Note 2: the result is the a string without leading zeros, so zero pad accordingly.
注意2:结果是一个没有前导0的字符串,因此0填充。
#3
153
Try
试一试
num.toString(2);
The 2 is the radix and can be any base between 2 and 36
2是基数,可以是2到36之间的任何底数
source here
源在这里
UPDATE:
更新:
This will only work for positive numbers, Javascript represents negative binary integers in two's-complement notation. I made this little function which should do the trick, I haven't tested it out properly:
这只适用于正数,Javascript用二补符号表示负二进制整数。我做了一个小函数,这个函数应该很有用,我还没有对它进行正确的测试:
function dec2Bin(dec)
{
if(dec >= 0) {
return dec.toString(2);
}
else {
/* Here you could represent the number in 2s compliment but this is not what
JS uses as its not sure how many bits are in your number range. There are
some suggestions https://*.com/questions/10936600/javascript-decimal-to-binary-64-bit
*/
return (~dec).toString(2);
}
}
I had some help from here
我从这里得到了一些帮助
#4
38
The binary in 'convert to binary' can refer to three main things. The positional number system, the binary representation in memory or 32bit bitstrings. (for 64bit bitstrings see Patrick Roberts' answer)
二进制在“转换成二进制”可以指三个主要的东西。位置数字系统、内存中的二进制表示或32位位位字符串。(关于64位比特串,请参阅帕特里克·罗伯茨的回答)
1. Number System
1。数字系统
(123456).toString(2)
will convert numbers to the base 2 positional numeral system. In this system negative numbers are written with minus signs just like in decimal.
(123456). tostring(2)将会将数字转换为基本的2位置数字系统。在这个系统中负数是用负号写的,就像小数一样。
2. Internal Representation
2。内部表示
The internal representation of numbers is 64 bit floating point and some limitations are discussed in this answer. There is no easy way to create a bit-string representation of this in javascript nor access specific bits.
数字的内部表示是64位浮点数,在这个答案中讨论了一些限制。在javascript中创建位字符串表示形式或访问特定位是不容易的。
3. Masks & Bitwise Operators
3所示。面具&按位运算符
MDN has a good overview of how bitwise operators work. Importantly:
MDN很好地概述了位运算符的工作方式。重要的是:
Bitwise operators treat their operands as a sequence of 32 bits (zeros and ones)
位运算符将其操作数视为32位(0和1)的序列
Before operations are applied the 64 bit floating points numbers are cast to 32 bit signed integers. After they are converted back.
在应用操作之前,将64位浮点数转换为32位有符号整数。在他们皈依之后。
Here is the MDN example code for converting numbers into 32-bit strings.
这里是将数字转换为32位字符串的MDN示例代码。
function createBinaryString (nMask) {
// nMask must be between -2147483648 and 2147483647
for (var nFlag = 0, nShifted = nMask, sMask = ""; nFlag < 32;
nFlag++, sMask += String(nShifted >>> 31), nShifted <<= 1);
return sMask;
}
createBinaryString(0) //-> "00000000000000000000000000000000"
createBinaryString(123) //-> "00000000000000000000000001111011"
createBinaryString(-1) //-> "11111111111111111111111111111111"
createBinaryString(-1123456) //-> "11111111111011101101101110000000"
createBinaryString(0x7fffffff) //-> "01111111111111111111111111111111"
#5
34
A simple way is just...
简单的方法就是……
Number(42).toString(2);
// "101010"
#6
8
Note- the basic (x>>>0).toString(2);
has a slight issue when x is positive. I have some example code at the end of my answer that corrects that problem with the >>> method while still using >>>.
注:基本(x > > > 0).toString(2);当x是正的时候有一个小问题。在我的答案后面有一些示例代码,它纠正了>>>方法的问题,但仍然使用>>>。
(-3>>>0).toString(2);
prints -3 in 2s complement.
1111111111101
A working example
一个工作示例
C:\>type n1.js
console.log( (-3 >>> 0).toString(2) );
C:\>
C:\>node n1.js
11111111111111111111111111111101
C:\>
This in the URL bar is another quick proof
这个在URL栏中是另一个快速证明。
javascript:alert((-3>>>0).toString(2))
Note- The result is very slightly flawed, in that it always starts with a 1, which for negative numbers is fine. For positive numbers you should prepend a 0 to the beginning so that the result is really 2s complement. So (8>>>0).toString(2)
produces 1000 which isn't really 8 in 2s complement, but prepending that 0, making it 01000, is correct 8 in 2s complement. In proper 2s complement, any bit string starting with 0 is >=0, and any bit string starting with 1, is negative.
注意——结果是有一点点瑕疵的,因为它总是以1开头,这对于负数是可以的。对于正数,你应该把0放在前面,这样结果就是2s的补码。所以(8>>>0)。tostring(2)生成的不是2s轨道的8,而是在0之前,得到的01000,是2s轨道的8。在固有的2s补码中,任何以0开头的位串都是>=0,而任何以1开头的位串都是负的。
e.g. this gets round that problem
这解决了那个问题
// or x=-5 whatever number you want to view in binary
x=5;
if(x>0) prepend="0"; else prepend="";
alert(prepend+((x>>>0)).toString(2));
The other solutions are the one from Annan(though Annan's explanations and definitions are full of errors, he has code that produces the right output), and the solution from Patrick.
其他的解决方案来自安南(尽管安南的解释和定义充满了错误,他的代码产生了正确的输出),以及帕特里克的解决方案。
Anybody that doesn't understand the fact of positive numbers starting with 0 and negative numbers with 1, in 2s complement, could check this SO QnA on 2s complement. What is “2's Complement”?
任何不理解0开头的正数和1开头的负数的人,在2s轨道中,都可以检查这个所以QnA在2s轨道上。“2的补”是什么?
#7
6
You can write your own function that returns an array of bits. Example how to convert number to bits
您可以编写自己的函数来返回一个位数组。示例如何将数字转换为位
Divisor| Dividend| bits/remainder
2 | 9 | 1
2 | 4 | 0
2 | 2 | 0
~ | 1 |~
example of above line: 2 * 4 = 8 and remainder is 1 so 9 = 1 0 0 1
上面一行的例子:2 * 4 = 8,余数为1,所以9 = 1 0 0 1
function numToBit(num){
var number = num
var result = []
while(number >= 1 ){
result.unshift(Math.floor(number%2))
number = number/2
}
return result
}
Read remainders from bottom to top. Digit 1 in the middle to top.
从下到上读出余数。从中间到上面的数字1。
#8
-2
This is my code:
这是我的代码:
var x = prompt("enter number", "7");
var i = 0;
var binaryvar = " ";
function add(n) {
if (n == 0) {
binaryvar = "0" + binaryvar;
}
else {
binaryvar = "1" + binaryvar;
}
}
function binary() {
while (i < 1) {
if (x == 1) {
add(1);
document.write(binaryvar);
break;
}
else {
if (x % 2 == 0) {
x = x / 2;
add(0);
}
else {
x = (x - 1) / 2;
add(1);
}
}
}
}
binary();
#9
-2
This is the solution . Its quite simple as a matter of fact
这就是答案。其实很简单
function binaries(num1){
var str = num1.toString(2)
return(console.log('The binary form of ' + num1 + ' is: ' + str))
}
binaries(3
)
/*
According to MDN, Number.prototype.toString() overrides
Object.prototype.toString() with the useful distinction that you can
pass in a single integer argument. This argument is an optional radix,
numbers 2 to 36 allowed.So in the example above, we’re passing in 2 to
get a string representation of the binary for the base 10 number 100,
i.e. 1100100.
*/