问题
Wondering how to convert the output of arbitrarily sized integers like 1 or 12345 or 5324617851000199519157 to an array of integers.
[1] // for the first one
// [probably just a few values for the second 12345...]
[1, 123, 255, 32, ...] // not sure here...
I am not sure what the resulting value would look like or how to compute it, but somehow it would be something like:
A bunch of 8-bit numbers that can be used to reconstruct (somehow) the original arbitrary integer. I am not sure what calculations would be required to do this either. But all I do know is that each unique arbitrarily-sized integer should result in a unique array of 8-bit values. That is, no two different date integers should result in the same array.
It doesn't matter the language much how this is implemented, but probably an imperative language like JavaScript or C.
I am pretty sure the arrays should all be the same length as well, but if that's not possible then knowing how to do it a different way would be okay.
回答1:
I'm not sure if this is too brute-forcey for what you want, but you can take an arbitrary string and just do the long division into a unit8Array.
Here's a function (borrowed liberally from here) that will convert back and forth from an arbitrarily long string:
function eightBit(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 eightBit2String(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('')
}
// sanity check
console.log("256 = ", eightBit('256'), "258 = ", eightBit('258'))
let n = '47171857151875817758571875815815782572758275672576575677'
let a = eightBit(n)
console.log("to convert:", n)
console.log("converted:", a.toString())
let s = eightBit2String(a)
console.log("converted back:", s)
No doubt, there are some efficiencies to be found (maybe you can avoid the interim arrays).
回答2:
Most languages, including C and Javascript, have bit-shifting and bit-masking operations as part of their basic math operations. But beware Javascript: numbers are 64 bits, but only 32-bit masking operations are allowed. So:
let bignum = Date.now();
let hi = Math.floor(bignum / 0x100000000),
lo = bignum & 0xFFFFFFFF,
bytes = [
(hi >> 24) & 0xFF,
(hi >> 16) & 0xFF,
(hi >> 8) & 0xFF,
hi & 0xFF,
(lo >> 24) & 0xFF,
(lo >> 16) & 0xFF,
(lo >> 8) & 0xFF,
lo & 0xFF
];
来源:https://stackoverflow.com/questions/53402560/how-to-split-large-integer-into-an-array-of-8-bit-integers