如何将大整数拆分为8位整数数组 [英] How to split large integer into an array of 8-bit integers
问题描述
想知道如何转换任意大小的整数的输出,如 1
或 12345
或 5324617851000199519157
到一个整数数组。
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:
一堆8位数字,可用于重建(以某种方式)原始任意整数。我不确定要做什么计算也是如此。但我所知道的是,每个唯一的任意大小的整数应该产生一个8位值的唯一数组。也就是说,没有两个不同的日期整数应该产生相同的数组。
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.
语言与实现方式无关,但可能是JavaScript等命令式语言或者C.
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.
推荐答案
我不确定这对你想要的东西是否过于暴力,但你可以采取任意的字符串只需将长除法划分为 unit8Array
。
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
.
这是一个函数(从 where )将从任意长的字符串来回转换:
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).
这篇关于如何将大整数拆分为8位整数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!