将给定数字转换成二进制字符串。如果字符串长度不足 8 位,则在前面补 0 到满8位。
例如输入:
65
输出:
01000001
// 方法一:最简单toString,padStart var num = 666; var rel = num.toString(2); console.log(rel); if (rel.length <= 8) { var rels = rel.padStart(8, '0'); console.log(rels); } else { console.log(rel); } // 方法二:不用padStart var num = 666; var rel = num.toString(2); //得到二进制数 if (rel.length < 8) { var tempnum = 8 - rel.length; console.log(tempnum); var temprel = '' for (var i = 0; i < tempnum; i++) { temprel += '0'; } console.log(temprel); var total = temprel + rel; console.log(total); } else { console.log(rel); } // 方法三:不用toString,使用vue var mv = new Vue({ el: '#app', data: { num: 0, result: 0 }, methods: { operate: function() { var arr = []; do { var value = parseInt(this.num / 2); var tempnum = this.num % 2; arr.unshift(tempnum); this.num = value; } while (value >= 1); var nums = 8 - arr.length; if (arr.length <= 8) { for (var i = 0; i < nums; i++) { arr.unshift(0); }; }; console.log(arr); this.result = arr.join(''); } } })
标签:二进制,var,length,给定,rel,字符串 From: https://www.cnblogs.com/zhaofen/p/17115665.html