2012-09-14 68 views
0

表示這是一個荒謬的問題,我在腦海裏想了一段時間,但讓我們說我想顯示一個非常非常大的數字,不能用普通的原語(或基元的組合)表示,所以我想在內存中可以使用一個字節數組。顯示非常大的數字,用byte []

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

+4

不使用預先存在BIGNUM圖書館有什麼特別的原因嗎? –

+1

你想打印二進制,八進制,十六進制,十進制,基地 - ( - 2)等等? –

+0

@KevinBallard只是因爲我想知道 –

回答

4

最簡單的(以實現和理解)。將10反覆把數,收集剩餘部分,例如:

一十分之一千二百三十四= 123,4
一十分之一百二十三= 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