2013-05-11 119 views
1

我用C++c + +轉換大數爲十六進制

我做了一個在線轉換大批這個值的

DECIMAL: 3712299789313814843 

我想將其轉換爲十六進制,我意識到了

hexadecimal value is  3384BCFD61CEB13B 

我在網上發現了一些解決方案,我嘗試轉換,但它給我這個:

string hex_value(int decimal) 
{ 
    static const string hex_digits("ABCDEF"); 

    string hex; 
    int scratch = decimal; 

    while (scratch != 0) 
    { 
    hex += hex_digits[scratch % 16]; 
    scratch /= 16; 
    } 

    reverse(hex.begin(), hex.end()); 

    return hex; 
} 

input= hex_value(atoi(buffer.c_str())); 



HEXA: 61CEB13B 

我覺得整數太小,在數據發送..我用NTL,即ZZ類,但我不知道如何在這種情況下使用它..

任何人都可以指導我如何轉換這大數變成十六進制..

謝謝!!

回答

1

您將需要某種大型圖書館,如BigInteger(https://mattmccutchen.net/bigint/)。一個32位整數只能保存一個大約40億左右的值(如果它是無符號的 - 如果它被簽名的話只有20億左右)。

如果scratch被聲明爲BigInteger而不是int,那麼您在問題中發佈的解決方案將工作得很好。

編輯:此外,只是供參考,疲憊的在線轉換器檢查您的答案。許多在線轉換器只使用32位整數,因此會給你一個錯誤的答案。

+1

有什麼不對的64位整數? (a.k.a'int64_t'?) – qdii 2013-05-11 17:24:35

+0

從技術上來說,沒有什麼是錯的64位int爲OP指定的號碼,但OP實際上即使在運行相當接近的與64號位的限制。無符號的64位int可以指望高達1.8 * 10^19。 OP處理的數量是3.7 * 10^18。作爲溢出是一個數量級之內,OP會很好地去大的INT大小的情況下,他/她必須面對更大的數字。 – 2to1mux 2013-05-12 00:03:17

0

在你的情況下,你使用的int十進制是非常小的來處理這麼大的數字。使用NTL與普通的int相同,所以你可以直接對它執行操作。同時代替while(scratch!= 0)使用while(十進制!= 0),這裏decimal將是ZZ類型。

你可以查看這個鏈接的例子。

http://www.shoup.net/ntl/doc/tour-ex1.html

0

我建議使用的庫gmp表示大的數字:它是非常直觀,非常簡單。它主要用於C語言,但有一些C++的擴展使事情變得更簡單。

這樣的圖書館代表你的大號碼後,你就可以申請步驟轉換爲十六進制:

設N是您的號碼:

  1. 初始化一個空字符串資源
  2. 計算N模16(提醒分部)
  3. 代表你在十六進制中獲得的值爲一個字符串:ex。10變爲 「一」
  4. 結果附加到RES
  5. N = N/16(整數除法)從所述第二步驟
  6. 重複直到N變爲0 -

我會給下面的例子:

#include <gmp.h> //contains all the functions and types 
    #include <gmpxx.h> //contains some classes for C++ 
    string toFormatFromDecimal(mpz_class t); 

    int main() 
    { 
     mpz_class N = "3712299789313814843"; //string initialisation 
     std::cout<<toFormatDecimal(N); 
     return 0; 
    } 

    string toFormatFromDecimal(mpz_class t)//mpz_class is the C++ equivalent of mpz_t 
    { 
     static const char hexmap[] = {'0', '1', '2', '3', '4', '5', '6', '7', 
         '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; 

     string res = ""; 
     mpz_t temp; //C variable to store a big number 
     mpz_init_set_ui(temp, 0); //initialisation 
     unsigned int pos; 
     do { 
      pos = mpz_mod_ui(temp, t.get_mpz_t(), 16); //calculate the reminder: t%16 
      res = res+hexmap[pos] ; 
      t = t/16; 

     } while ((mpz_cmp_ui(t.get_mpz_t(), 0) != 0)); 

     return string(res.rbegin(), res.rend()); 
    }