Javascript parseInt 不将十进制转换为二进制?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31126364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
parseInt not converting decimal to binary?
提问by Robert Rocha
From my understanding the binary number system uses as set of two numbers, 0's and 1's to perform calculations.
根据我的理解,二进制数系统使用一组两个数字,0 和 1 来执行计算。
Why does:
为什么:
console.log(parseInt("11", 2));
return 3
and not 00001011
?
http://www.binaryhexconverter.com/decimal-to-binary-converter
console.log(parseInt("11", 2));
返回3
而不是00001011
?
http://www.binaryhexconverter.com/decimal-to-binary-converter
回答by Walter Chapilliquen - wZVanG
Use toString()instead of parseInt
:
使用toString()代替parseInt
:
11..toString(2)
var str = "11";
var bin = (+str).toString(2);
console.log(bin)
According JavaScript's Documentation:
根据 JavaScript 的文档:
The following examples all return NaN:
parseInt("546", 2);
// Digits are not valid for binary representations
以下示例均返回 NaN:
parseInt("546", 2);
//数字对于二进制表示无效
回答by Robo Robok
parseInt(number, base)
returns decimalvalue of a number presented by number
parameter in base
base.
parseInt(number, base)
返回由base 中的参数表示的数字的十进制值。number
base
And 11 is binary equivalent of 3 in decimal number system.
11 是十进制数系统中 3 的二进制等价物。
var a = {};
window.addEventListener('input', function(e){
a[e.target.name] = e.target.value;
console.clear();
console.log( parseInt(a.number, a.base) );
}, false);
<input name='number' placeholder='number' value='1010'>
<input name='base' placeholder='base' size=3 value='2'>
回答by Jason Cust
As stated in the documentation for parseInt
: The parseInt() function parses a string argument and returns an integer of the specified radix(the base in mathematical numeral systems).
如文档parseInt
中所述:parseInt() 函数解析字符串参数并返回指定基数(数学数字系统中的基数)的整数。
So, it is doing exactly what it should do: converting a binary value of 11
to an integer value of 3
.
因此,它正在做它应该做的事情:将 的二进制值转换11
为 的整数值3
。
If you are trying to convert an integer value of 11
to a binary value than you need to use the Number.toString
method:
如果您尝试将 的整数值转换11
为二进制值,则需要使用以下Number.toString
方法:
console.log(11..toString(2)); // 1011
回答by alamnaryab
.toString(2)
works when applied to a Number
type.
.toString(2)
应用于Number
类型时有效。
255.toString(2) // syntax error
"255".toString(2); // 255
var n=255;
n.toString(2); // 11111111
// or in short
Number(255).toString(2) // 11111111
// or use two dots so that the compiler does
// mistake with the decimal place as in 250.x
255..toString(2) // 11111111
回答by Melchia
The shortes method I've found for converting a decimal stringinto a binary is:
我发现的用于将十进制字符串转换为二进制的 shortes 方法是:
const input = "54654";
const output = (input*1).toString(2);
print(output);
回答by Simon Wang
The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).
parseInt() 函数解析字符串参数并返回指定基数(数学数字系统中的基数)的整数。
So you are telling the system you want to convert 11 as binary to an decimal.
所以你告诉系统你想将 11 作为二进制转换为十进制。
Specifically to the website you are referring, if you look closer it is actually using JS to issue a HTTP GET to convert it on web server side. Something like following:
具体到您所指的网站,如果您仔细观察,它实际上是使用 JS 发出 HTTP GET 以在 Web 服务器端进行转换。类似于以下内容:
http://www.binaryhexconverter.com/hesapla.php?fonksiyon=dec2bin°er=11&pad=false
http://www.binaryhexconverter.com/hesapla.php?fonksiyon=dec2bin°er=11&pad=false
回答by Teocci
This is an old question, however I have another solution that might contribute a little bit. I usually use this function to convert a decimal number into a binary:
这是一个老问题,但是我有另一个可能会有所贡献的解决方案。我通常使用此函数将十进制数转换为二进制数:
function dec2bin(dec) {
return (dec >>> 0).toString(2);
}
The dec >>> 0
converts the number into a byte and then toString(radix)
function is called to return a binary string. It is simple and clean.
该dec >>> 0
转换成字节,然后数toString(radix)
函数被调用返回的二进制字符串。它简单干净。
Note: a radix
is used for representing a numeric value. Must be an integer between 2 and 36. For example:
注:aradix
用于表示数值。必须是 2 到 36 之间的整数。例如:
- 2 - The number will show as a binary value
- 8 - The number will show as an octal value
- 16 - The number will show as an hexadecimal value
- 2 - 数字将显示为二进制值
- 8 - 数字将显示为八进制值
- 16 - 数字将显示为十六进制值
回答by anshul
I think you should understand the math behind decimal to binary conversion. Here is the simple implementation in javascript.
我认为您应该了解十进制到二进制转换背后的数学原理。这是javascript中的简单实现。
main();
function main() {
let input = 12;
let result = decimalToBinary(input);
console.log(result);
}
function decimalToBinary(input) {
let base = 2;
let inputNumber = input;
let quotient = 0;
let remainderArray = [];
let resultArray = [];
if (inputNumber) {
while (inputNumber) {
quotient = parseInt(inputNumber / base);
remainderArray.push(inputNumber % base);
inputNumber = quotient;
}
for (let i = remainderArray.length - 1; i >= 0; i--) {
resultArray.push(remainderArray[i]);
}
return parseInt(resultArray.join(''));
} else {
return `${input} is not a valid input`;
}
}
回答by jaykay
This worked for me: parseInt(Number, original_base).toString(final_base)
这对我有用: parseInt(Number, original_base).toString(final_base)
Eg: parseInt(32, 10).toString(2) for decimal to binary conversion.
例如: parseInt(32, 10).toString(2) 用于十进制到二进制的转换。
Source: https://www.w3resource.com/javascript-exercises/javascript-math-exercise-3.php
来源:https: //www.w3resource.com/javascript-exercises/javascript-math-exercise-3.php
回答by Isaac
Here is a concise recursive version of a manualdecimal to binary algorithm:
这是手动十进制到二进制算法的简明递归版本:
- Divide decimal number in half and aggregate remainder per operation until value==0 and print concatenated binary string
Example using 25: 25/2 = 12(r1)/2 = 6(r0)/2 = 3(r0)/2 = 1(r1)/2 = 0(r1) => 10011 => reverse => 11001
function convertDecToBin(input){ return Array.from(recursiveImpl(input)).reverse().join(""); //convert string to array to use prototype reverse method as bits read right to left function recursiveImpl(quotient){ const nextQuotient = Math.floor(quotient / 2); //divide subsequent quotient by 2 and take lower limit integer (if fractional) const remainder = ""+quotient % 2; //use modulus for remainder and convert to string return nextQuotient===0?remainder:remainder + recursiveImpl(nextQuotient); //if next quotient is evaluated to 0 then return the base case remainder else the remainder concatenated to value of next recursive call } }
- 将十进制数一分为二并聚合每个操作的余数,直到 value==0 并打印连接的二进制字符串
使用 25 的示例:25/2 = 12(r1)/2 = 6(r0)/2 = 3(r0)/2 = 1(r1)/2 = 0(r1) => 10011 => 反向 => 11001
function convertDecToBin(input){ return Array.from(recursiveImpl(input)).reverse().join(""); //convert string to array to use prototype reverse method as bits read right to left function recursiveImpl(quotient){ const nextQuotient = Math.floor(quotient / 2); //divide subsequent quotient by 2 and take lower limit integer (if fractional) const remainder = ""+quotient % 2; //use modulus for remainder and convert to string return nextQuotient===0?remainder:remainder + recursiveImpl(nextQuotient); //if next quotient is evaluated to 0 then return the base case remainder else the remainder concatenated to value of next recursive call } }