如果要对数组求和,如何计算字节[]中的总位数



我想做一个函数,一旦值被相加,就计算位数

假设我有这个阵列

byte[] array = new byte[] { 200, 100, 200, 250, 150, 100, 200 };

一旦这些加起来,你就会得到1200 的值

你可以用这些功能得到位数

Math.Floor(Math.Log10(1200)+1) // 4

但如果我把它加起来,数组中的值太多,我会得到一个整数溢出

public decimal countDigits(byte[] array)
{
decimal count = array[0];
for (int i = 1; i < array.Length; i++)
{
count = Math.Log10(Math.Pow(count, 10)+array[i]);
}
return count;
}

这确实给出了我想要的正确输出,但如果计数大于28.898879583742193(log10(decimal.MaxValue((,则会导致整数溢出

让我们提出一个简单的问题:为了用long获得整数溢出,我们应该求和多少byte?答案很简单:在最坏的情况下(所有字节都是最大可能值(,它需要

long.MaxValue / byte.MaxValue + 1 = 36170086419038337 (~3.61e16) bytes

我们要求和多久?即使只需要1cputick(~ 0.1ns(就可以从数组中获取项并求和~3.6e6秒,即41天(或在ulong的情况下82日(。如果不是您的情况(注意,当我们想要至少3.6e16时,C#中的数组不能有超过2.1e9个项目(,那么您可以将其求和为long(或ulong(:

public static int countNumbers(byte[] array) {
ulong sum = 0;
foreach (byte item in array)
sum += item;
// How many digits do we have?
return sum.ToString().Length;
}

i want to make a function that counts the amount of digits once the value is sumed up

public decimal countNumbers(byte[] array)
{
// sum the values...
decimal sum = 0;
foreach (byte value in array)
{
sum += value 
}
// ... then "count" the digits.
return Math.Floor(Math.Log10(sum)+1);
}

这将是代码,然而,您的问题、提供的示例和方法的命名都意味着不同的东西,所以看看这是否有帮助,如果有帮助,请进行命名。

有一个BigInteger数据类型,它可以对任意(整数(值求和。它甚至有一个Log10方法,所以它的工作方式与标准整数变量非常相似。唯一的限制是BigInteger.Log10的结果必须小于Double.MaxValue,但这听起来是一个合理的限制。(10^1E308=10^10^308是一个非常大的数字(

最新更新