# converting from byte arrays to strings of integers, and back

I have this code to go from an array of bytes (arbitrarily long) to a "bigint" string (really, an arbitrarily long string composed of integers 0-9), and go from that long integer string into an array of bytes.

console.log(bigintStringToBytes('12321232123213213292948428924184'))
console.log(bytesToBigintString([ 155, 132, 12, 85, 200, 76, 41, 241, 14, 133, 71, 165, 24 ]))

function bigintStringToBytes(str) {
let dec = [...str],  sum = []
while(dec.length){
let s = 1 * dec.shift()
for(let i = 0; s || i < sum.length; i++){
s += (sum[i] || 0) * 10
sum[i] = s % 256
s = (s - sum[i]) / 256
}
}
return Uint8Array.from(sum.reverse())
}

function bytesToBigintString(arr) {
var dec = [...arr], sum = []
while(dec.length){
let s = 1 * dec.shift()
for(let i = 0; s || i < sum.length; i++){
s += (sum[i] || 0) * 256
sum[i] = s % 10
s = (s - sum[i]) / 10
}
}
return sum.reverse().join('')
}

How can these two functions be optimized?

• Do you have other test cases that need to pass, or some general constraint on how this needs to work? These functions look to me like they're doing something odd (not just a plain old base conversion), but if you're OK with that then sure why not. Also, is using the new-ish built-in BigInt allowed? Aug 19, 2021 at 21:52
• If BigInt works, yeah you can use that. What other information do you need, I don't have any other test cases to pass, just plugin input and output and make sure they match up with each function. Then you could try optimizing the functions so the inputs/outputs are still the same. It should be any "digitized" string, converted to equivalent byte array representation, and back. Aug 20, 2021 at 2:36
• Can the string version be hexadecimal? That would avoid the main complicating factor Aug 20, 2021 at 2:40
• No the string needs to be integers, but if you wanted to share the hexadecimal solution as well that would be a plus :) Aug 20, 2021 at 2:44