我已經看到幾個將數字從十進制轉換爲十六進制(或基數10轉換爲十六進制)的示例,但我對於所嘗試的有幾個限制去做。我需要能夠將十進制數字的字符串轉換爲另一個字符串作爲十六進制數字。該數字可能太大而不適合在任何原始數據類型中 - 即:不能使用整數,無符號整數,雙精度等...在C++中將任意長度的數字從十進制轉換爲十六進制
這應該能夠執行與本頁上列出的相同的計算。 http://www.kaagaard.dk/service/convert.htm
我試過這個,但它沒有爲我工作。
給函數的調用:
const int maxLen = 256;
char destination[maxLen];
int retVal = convertBase(destination, maxLen, "123487032174829820348320429437483266812812");
函數定義:
int convertBase(char* dest, int maxDestLength, const char* inputInBase10)
{
const char lookUpTable[] = { "abcdef" };
const std::string input = inputInBase10;
const unsigned int inputSize = input.length();
std::string output;
output.reserve(2 * inputSize);
for(unsigned int i = 0; i < inputSize; ++i)
{
const unsigned char c = input[i];
output.push_back(lookUpTable[c >> 4]);
output.push_back(lookUpTable[c & 15]);
}
if(output.length() < maxDestLength)
strcpy_s(dest, output.length(), output.c_str());
else
strcpy_s(dest, maxDestLength, output.c_str());
cout << dest << endl;
return strlen(dest);
}
預期的十六進制數: 「16ae5514d07e120126dfbcb3073fddb2b8c」
實際產生的十六進制數: 「313233343837303332313734383239383230333438333230343239343337343833323636383132383132」
另外,我不斷收到一個錯誤,傳遞迴一個char *當緩衝區太小(下面重複)
if(output.length() < maxDestLength)
strcpy_s(dest, output.length(), output.c_str());
else
strcpy_s(dest, maxDestLength, output.c_str());
您正在將輸入字符串中數字的ASCII值轉換爲十六進制,而不是輸入字符串表示的實際數字。 – 2013-03-25 03:06:25
這裏有一個提示:你得到的輸出(「313233343837」)看起來像你的輸入號碼字符的ASCII值(在字符串中編碼爲十六進制字節) 0x38 =='8' – 2013-03-25 03:06:29
一般來說,你需要爲這種事情做長時間的劃分,但是當你沒有長時間的劃分時,你可以用一系列的補充來構建它。這是否必須是最佳的?我有一個非最優但簡單的解決方案。 – paddy 2013-03-25 03:35:40