在JavaScript中将前导零添加到二进制字符串的方法 [英] Way to add leading zeroes to binary string in JavaScript
本文介绍了在JavaScript中将前导零添加到二进制字符串的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用.toString(2)将整数转换为二进制,但只要需要它就返回一个二进制(即第一位是1)。
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).
所以其中:
num = 2;
num.toString(2) // yields 10.
如何产生八位位组00000010?
How do I yield the octet 00000010?
推荐答案
这很简单
var n = num.toString(2);
n = "00000000".substr(n.length) + n;
这篇关于在JavaScript中将前导零添加到二进制字符串的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文