在 JavaScript 中为二进制字符串添加前导零的方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27641812/
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
Way to add leading zeroes to binary string in JavaScript
提问by zahabba
I've used .toString(2) to convert an integer to a binary, but it returns a binary only as long as it needs to be (i.e. first bit is a 1).
我已经使用 .toString(2) 将整数转换为二进制,但它仅在需要时返回二进制(即第一位是 1)。
So where:
那么在哪里:
num = 2;
num.toString(2) // yields 10.
How do I yield the octet 00000010?
我如何产生八位字节 00000010?
回答by Joe Thomas
It's as simple as
就这么简单
var n = num.toString(2);
n = "00000000".substr(n.length) + n;
回答by forgivenson
You could just add zeroes on the front of the result until it is the correct length.
您可以在结果的前面添加零,直到它是正确的长度。
var num = 2,
binaryStr = num.toString(2)i;
while(binaryStr.length < 8) {
binaryStr = "0" + binaryStr;
}
回答by rfornal
Try something like this ...
尝试这样的事情......
function pad(n, width, z) {
z = z || '0';
n = n + '';
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
... then use it as ...
...然后将其用作...
pad(num.toString(2), 8);