为什么要单独写个方法去做不同进制之间的转换呢?因为自带的方法在进行十六进制转为二进制的时候,精度在13位字符后就会出现丢失,为了让精度不丢失就自己根据16进制转换2进制的原理写了两个方法
如果长度没有超过13位,可以用parseInt("125adf8",16).toString(2)='1001001011010110111111000',
十六进制转换二进制 (本次转换的方法没有考虑带小数点的情况)
function hex_to_bin(str) {
let hex_array = [{key:0,val:"0000"},{key:1,val:"0001"},{key:2,val:"0010"},{key:3,val:"0011"},{key:4,val:"0100"},{key:5,val:"0101"},{key:6,val:"0110"},{key:7,val:"0111"},
{key:8,val:"1000"},{key:9,val:"1001"},{key:'a',val:"1010"},{key:'b',val:"1011"},{key:'c',val:"1100"},{key:'d',val:"1101"},{key:'e',val:"1110"},{key:'f',val:"1111"}]
let value=""
for(let i=0;i<str.length;i++){
for(let j=0;j<hex_array.length;j++){
if(str.charAt(i).toLowerCase()== hex_array[j].key){
value = value.concat(hex_array[j].val)
break
}
}
}
console.log(value)
return value
}
二进制转十六进制 (本次转换的方法没有考虑带小数点的情况)
function bin_to_hex(str) {
let hex_array = [{key:0,val:"0000"},{key:1,val:"0001"},{key:2,val:"0010"},{key:3,val:"0011"},{key:4,val:"0100"},{key:5,val:"0101"},{key:6,val:"0110"},{key:7,val:"0111"},
{key:8,val:"1000"},{key:9,val:"1001"},{key:'a',val:"1010"},{key:'b',val:"1011"},{key:'c',val:"1100"},{key:'d',val:"1101"},{key:'e',val:"1110"},{key:'f',val:"1111"}]
let value = ''
let list=[]
console.log(str)
if(str.length%4!==0){
let a = "0000"
let b=a.substring(0,4-str.length%4)
str = b.concat(str)
}
console.log(str)
while (str.length > 4) {
list.push(str.substring(0, 4))
str = str.substring(4);
}
list.push(str)
console.log(list)
for(let i=0;i<list.length;i++){
for(let j=0;j<hex_array.length;j++){
if(list[i]==hex_array[j].val){
value = value.concat(hex_array[j].key)
break
}
}
}
console.log(value)
return value
}
异或运算 (需要上面两个方法做基础)
function xor(a ,b){
let A = hex_to_bin(a)
let B = hex_to_bin(b)
console.log(a+" a的二进制:"+A)
console.log(b+" b的二进制:"+B)
let o = "00000000000000000000000000000000000"
if(A.toString().length > B.toString().length){
let c = A.toString().length - B.toString().length
B = o.substr(0,c).concat(B)
}else if(A.toString().length < B.toString().length){
let c = B.toString().length - A.toString().length
A = o.substr(0,c).concat(A)
}
console.log('B:'+B)
console.log('A:'+A)
let d = ""
for(let i=0;i<A.toString().length;i++){
if(A.toString()[i]==B.toString()[i]){
let q="0"
d = d.concat(q)
}else{
let p="1"
d = d.concat(p)
}
}
console.log(bin_to_hex(d))
return bin_to_hex(d)
}
版权声明:本文为博主原创文章,未经博主允许不得转载。https://blog.csdn.net/lixiwoaini/article/details/82179094