簡體   English   中英

顯示非常大的數字,由byte []表示

[英]Displaying very large numbers, represented by byte[]

這是一個荒謬的問題,我已經想到了一段時間,但是我想說我想顯示一個非常非常大的數字,一個不能用普通基元(或基元組合)表示的數字。 ..沒long long ... ),所以我想可以使用內存中的字節數組。

如果我有一個n字節的字節數組(其中n是大的)長度,我怎樣才能正確打印字節數組,好像它是一個十進制的十進制整數。 優選解釋而不僅僅是答案。

最簡單的(實現和理解)是將數字重復除以10,收集余數,例如:

1234/10 = 123,4
123/10 = 12,3
12/10 = 1,2
1/10 = 0,1

然后打印剩余部分(按相反順序)。

將字節序列除以10時,將每個字節分開,從最高有效字節開始。 並且您將余數從除法傳遞到下一個字節,直到您處理完所有字節為止。

int divBytesBy10(unsigned char* bytes, size_t count, unsigned char* remainder)
{
  unsigned carryOver = 0;
  int nonZeroQuotient = 0;

  while (count--)
  {
    carryOver = carryOver * 256 + *bytes;
    *bytes = carryOver / 10;
    carryOver %= 10;

    nonZeroQuotient |= *bytes++;
  }

  *remainder = carryOver;
  return nonZeroQuotient;
}

一個完整的例子:

#include <stdio.h>

int divBytesBy10(unsigned char* bytes, size_t count, unsigned char* remainder)
{
  unsigned carryOver = 0;
  int nonZeroQuotient = 0;

  while (count--)
  {
    carryOver = carryOver * 256 + *bytes;
    *bytes = carryOver / 10;
    carryOver %= 10;

    nonZeroQuotient |= *bytes++;
  }

  *remainder = '0' + carryOver; // convert to ASCII right here
  return nonZeroQuotient;
}

int main(void)
{
  unsigned char num[] = {0xFF, 0xFF, 0xFF, 0xFF};
  char str[11], *p = str + sizeof(str) - 1;
  *p = '\0';
  while (divBytesBy10(num, sizeof(num), --p)) {}
  printf("%s\n", p);
  return 0;
}

輸出( ideone ):

4294967295

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM