[英]JavaScript - Convert decimal number to 4-bit binary number in the form of String
I wrote a Javascript method that will take a decimal number input and gives a binary number in the form of string.我写了一个 Javascript 方法,它将接受十进制数输入并以字符串的形式给出一个二进制数。
Example 1:
Input: 15 Output : "1111" Example 1:
输入:15 输出:“1111”
The method I wrote works as follows:我写的方法如下:
If my input number is 15 ,如果我输入的数字是 15 ,
var t = parseInt(15,10).toString(2);
then output of t
will be "1111"那么t
输出将是“1111”
My question is how to convert a number lesser than 15 also as a 4-bit binary number string.我的问题是如何将小于 15 的数字也转换为 4 位二进制数字字符串。 As in,就像在,
Input: 4输入:4
Desired output : "0100" , but what I get right now is, "100" .所需的输出: "0100" ,但我现在得到的是 "100" 。
Please help me with the workaround.请帮助我解决方法。
The
padStart()
method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length.padStart()
方法用另一个字符串padStart()
当前字符串(多次,如果需要),直到结果字符串达到给定长度。 The padding is applied from the start of the current string.从当前字符串的开头应用填充。
var t1 = parseInt(4, 10).toString(2).padStart(4, "0") var t2 = parseInt(15, 10).toString(2).padStart(4, "0") console.log(t1) console.log(t2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.