我有一个任务,需要编写一个具有以下要求的编码器:
- 输入:1 到 8 位之间的整数(即 12345678、2352、76543)
- 输出:固定大小的 6 位数字代码,可以包含任何字母数字和符号(a-z、A-Z、0-9、!@#$%*()|-_=+^/?)
- 该操作必须是可逆的,因此给定一个代码,它应该解码回原始整数
- 输出代码无需加密安全
我没有加密(?)或编码算法的经验,所以我不知道如何完成这项工作。我在网上找到的库不允许设置输出大小,因为它是基于输入大小的。
非常感谢任何帮助,我在这里迷路了
最佳答案
当我看到这个时,我很兴奋,所以我做了一个至少满足问题要求的答案:D
编码通过基本转换逻辑并将这些数字转换为文本来工作。我使用长度为6的数组来存储编码数据,以确保它始终是6个字符(且不少于)
解码的工作原理是将其添加回来,尊重权力,因此它会以完整的值添加回来
我希望这是您正在寻找的答案,因为我喜欢这个问题:D
//a homemade answer :D
//first time I saw a question like that, I hope I get stuff like this in college ngl
function encode(num){
let alphabet=[]
for(let i=48;i<127;i++){
alphabet.push(String.fromCharCode(i))
}
//alphabet is filled with encoding text :D
let arr=[0,0,0,0,0,0] //for fixed 6 digits
let pow=0; let pow1=1
let length=alphabet.length
while(num>0){
let subtraction=(num%Math.pow(length,pow1))
num-=subtraction
arr[pow]=subtraction/Math.pow(length,pow)
pow++; pow1++
}
return arr.reverse()
.map(a=>String.fromCharCode(a+48)) //offset of 48 for nice chars
.join('') //like a base conversion basically
}
function decode(string){
let num=0; let length=127-48 //length really is the number of base(79 in this case)
string=string.split('').reverse().join('')
for(let i=0;i<string.length;i++){
let int=string.charCodeAt(i)-48 //-48 remembering the offset
num+=int*Math.pow(length,i)
}
return num
}
var int=12348291
console.log('encoded num:',encode(int))
console.log('decoded string:',decode(encode(int)))
console.log('they are reversible?',decode(encode(int))==int)
关于javascript - 字符串编码器固定大小输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67679881/