11

大きい(組み込みデータ型には大きすぎる)16進文字列を10進表現の文字列に変換する必要があります。例えば:

std::string sHex = "07AA17C660F3DD1D2A1B48F1B746C148";
std::string sDec; // should end up with: "10187768649047767717933300899576725832"

私は現在、これを達成するための非常に簡単な方法を提供するc ++ BigIntクラスを使用しています(ただし、GPLのみです)。

BigInt::Vin vbiTemp(sHex, 16);
sDec = vbiTemp.toStrDec();

サードパーティの算術ライブラリなしでこの変換を行う簡単な方法はありますか?または、同様の単純さ(効率は関係ありません)を備えた無料(非GPL)の代替案をお勧めできますか?

4

3 に答える 3

15

OK、これは一般的な基本コンバーター クラスです。元の実装は C# で作成し、これを C++ に変換しました。その .NET の起源は今でも輝きを放っている可能性があります。気分に合わせてご自由にお使いください。

次のように使用できます。

const BaseConverter& hex2dec = BaseConverter::HexToDecimalConverter();
std::cout << hex2dec.Convert("07AA17C660F3DD1D2A1B48F1B746C148");

出力は次のようになります。

10187768649047767717933300899576725832

クラスは 16 進数に限定されませんが、任意の基数エンコーディングを使用して、任意の基数間で喜んで変換されます。

API

  • BaseConverter::BaseConverter(const std::string& sourceBaseSet, const std::string& targetBaseSet);

    新しい BaseConverter インスタンスを構築します。このクラスは、ソース基数で表された数値をターゲット基数に変換します。

    コンストラクターは、2 つの文字列引数を使用して、ソースおよびターゲットの基数に使用する記号を指定します。文字列の最初の文字の値は0、2 番目の文字の値は1というようになります。例: 8 進数の基数の記号は通常"01234567"、16進数の記号は"0123456789ABCDEF"です。シンボルには印刷可能な任意の ASCII 文字を使用できます。バイナリ システム"OI"には ( の代わりに) を使用します。"01"

    : 基本記号は大文字と小文字が区別されるため、記号"0123456789abcdef"は大文字を使用して 16 進数をデコードしません。

  • std::string BaseConverter::Convert(std::string value) const;
    std::string BaseConverter::Convert(const std::string& value, size_t minDigits) const;

    valueソース基数の数値をターゲット基数に変換し、結果を返します。2 番目のオーバーロードは、追加のパラメーターを使用minDigitsして、結果の最小桁数を指定します。戻り値は、ターゲット基数で値0を持つ 0 個以上のシンボルを先頭に追加することによってパディングされます。

  • std::string BaseConverter::FromDecimal(unsigned int value) const;
    std::string BaseConverter::FromDecimal(unsigned int value, size_t minDigits) const;

    unsigned int 10 進数をターゲット基数に変換します。

  • unsigned int BaseConverter::ToDecimal(std::string value) const;

    ソース記数法の数値を 10 進数のunsigned intに変換します。: ソース ベース システムの数値の 10 進数値が UINT_MAX を超えると、結果が正しくなくなります。

  • static const BaseConverter& BaseConverter::DecimalToBinaryConverter();
    static const BaseConverter& BaseConverter::BinaryToDecimalConverter();
    static const BaseConverter& BaseConverter::DecimalToHexConverter();
    static const BaseConverter& BaseConverter::HexToDecimalConverter();

    BaseConverter一般的な基数間の変換に適したインスタンスを返す便利な関数。:大文字の A ~ F は、16 進数の基数に使用されます。

BaseConverter.h:

// Arbitrary precision base conversion by Daniel Gehriger <gehriger@linkcad.com>   

#include <string>

class BaseConverter
{
public:
    std::string GetSourceBaseSet() const { return sourceBaseSet_; }
    std::string GetTargetBaseSet() const { return targetBaseSet_; }
    unsigned int GetSourceBase() const { return (unsigned int)sourceBaseSet_.length(); }
    unsigned int GetTargetBase() const { return (unsigned int)targetBaseSet_.length(); }

    /// <summary>
    /// Constructor
    /// </summary>
    /// <param name="sourceBaseSet">Characters used for source base</param>
    /// <param name="targetBaseSet">Characters used for target base</param>
    BaseConverter(const std::string& sourceBaseSet, const std::string& targetBaseSet);

    /// <summary>
    /// Get a base converter for decimal to binary numbers
    /// </summary>
    static const BaseConverter& DecimalToBinaryConverter();

    /// <summary>
    /// Get a base converter for binary to decimal numbers
    /// </summary>
    static const BaseConverter& BinaryToDecimalConverter();

    /// <summary>
    /// Get a base converter for decimal to binary numbers
    /// </summary>
    static const BaseConverter& DecimalToHexConverter();

    /// <summary>
    /// Get a base converter for binary to decimal numbers
    /// </summary>
    static const BaseConverter& HexToDecimalConverter();

    /// <summary>
    /// Convert a value in the source number base to the target number base.
    /// </summary>
    /// <param name="value">Value in source number base.</param>
    /// <returns>Value in target number base.</returns>
    std::string  Convert(std::string value) const;


    /// <summary>
    /// Convert a value in the source number base to the target number base.
    /// </summary>
    /// <param name="value">Value in source number base.</param>
    /// <param name="minDigits">Minimum number of digits for returned value.</param>
    /// <returns>Value in target number base.</returns>
    std::string Convert(const std::string& value, size_t minDigits) const;

    /// <summary>
    /// Convert a decimal value to the target base.
    /// </summary>
    /// <param name="value">Decimal value.</param>
    /// <returns>Result in target base.</returns>
    std::string FromDecimal(unsigned int value) const;

    /// <summary>
    /// Convert a decimal value to the target base.
    /// </summary>
    /// <param name="value">Decimal value.</param>
    /// <param name="minDigits">Minimum number of digits for returned value.</param>
    /// <returns>Result in target base.</returns>
    std::string FromDecimal(unsigned int value, size_t minDigits) const;

    /// <summary>
    /// Convert value in source base to decimal.
    /// </summary>
    /// <param name="value">Value in source base.</param>
    /// <returns>Decimal value.</returns>
    unsigned int ToDecimal(std::string value) const;

private:
    /// <summary>
    /// Divides x by y, and returns the quotient and remainder.
    /// </summary>
    /// <param name="baseDigits">Base digits for x and quotient.</param>
    /// <param name="x">Numerator expressed in base digits; contains quotient, expressed in base digits, upon return.</param>
    /// <param name="y">Denominator</param>
    /// <returns>Remainder of x / y.</returns>
    static unsigned int divide(const std::string& baseDigits, 
                               std::string& x, 
                               unsigned int y);

    static unsigned int base2dec(const std::string& baseDigits,
                                 const std::string& value);

    static std::string dec2base(const std::string& baseDigits, unsigned int value);

private:
    static const char*  binarySet_;
    static const char*  decimalSet_;
    static const char*  hexSet_;
    std::string         sourceBaseSet_;
    std::string         targetBaseSet_;
};

BaseConverter.cpp:

// Arbitrary precision base conversion by Daniel Gehriger <gehriger@linkcad.com>   

#include "BaseConverter.h"
#include <stdexcept>
#include <algorithm>


const char* BaseConverter::binarySet_ = "01";
const char* BaseConverter::decimalSet_ = "0123456789";
const char* BaseConverter::hexSet_ = "0123456789ABCDEF";

BaseConverter::BaseConverter(const std::string& sourceBaseSet, const std::string& targetBaseSet) 
    : sourceBaseSet_(sourceBaseSet)
    , targetBaseSet_(targetBaseSet)
{
    if (sourceBaseSet.empty() || targetBaseSet.empty())
        throw std::invalid_argument("Invalid base character set");
}

const BaseConverter& BaseConverter::DecimalToBinaryConverter()
{
    static const BaseConverter dec2bin(decimalSet_, binarySet_);
    return dec2bin;
}

const BaseConverter& BaseConverter::BinaryToDecimalConverter()
{
    static const BaseConverter bin2dec(binarySet_, decimalSet_);
    return bin2dec;
}

const BaseConverter& BaseConverter::DecimalToHexConverter()
{
    static const BaseConverter dec2hex(decimalSet_, hexSet_);
    return dec2hex;
}

const BaseConverter& BaseConverter::HexToDecimalConverter()
{
    static const BaseConverter hex2dec(hexSet_, decimalSet_);
    return hex2dec;
}

std::string BaseConverter::Convert(std::string value) const
{
    unsigned int numberBase = GetTargetBase();
    std::string result;

    do
    {
        unsigned int remainder = divide(sourceBaseSet_, value, numberBase);
        result.push_back(targetBaseSet_[remainder]);
    }
    while (!value.empty() && !(value.length() == 1 && value[0] == sourceBaseSet_[0]));

    std::reverse(result.begin(), result.end());
    return result;
}

std::string BaseConverter::Convert(const std::string& value, size_t minDigits) const
{
    std::string result = Convert(value);
    if (result.length() < minDigits)
        return std::string(minDigits - result.length(), targetBaseSet_[0]) + result;
    else
        return result;
}

std::string BaseConverter::FromDecimal(unsigned int value) const
{
    return dec2base(targetBaseSet_, value);
}

std::string BaseConverter::FromDecimal(unsigned int value, size_t minDigits) const
{
    std::string result = FromDecimal(value);
    if (result.length() < minDigits)
        return std::string(minDigits - result.length(), targetBaseSet_[0]) + result;
    else
        return result;
}

unsigned int BaseConverter::ToDecimal(std::string value) const
{
    return base2dec(sourceBaseSet_, value);
}

unsigned int BaseConverter::divide(const std::string& baseDigits, std::string& x, unsigned int y)
{
    std::string quotient;

    size_t lenght = x.length();
    for (size_t i = 0; i < lenght; ++i)
    {
        size_t j = i + 1 + x.length() - lenght;
        if (x.length() < j)
            break;

        unsigned int value = base2dec(baseDigits, x.substr(0, j));

        quotient.push_back(baseDigits[value / y]);
        x = dec2base(baseDigits, value % y) + x.substr(j);
    }

    // calculate remainder
    unsigned int remainder = base2dec(baseDigits, x);

    // remove leading "zeros" from quotient and store in 'x'
    size_t n = quotient.find_first_not_of(baseDigits[0]);
    if (n != std::string::npos)
    {
        x = quotient.substr(n);
    }
    else
    {
        x.clear();
    }

    return remainder;
}

std::string BaseConverter::dec2base(const std::string& baseDigits, unsigned int value)
{
    unsigned int numberBase = (unsigned int)baseDigits.length();
    std::string result;
    do 
    {
        result.push_back(baseDigits[value % numberBase]);
        value /= numberBase;
    } 
    while (value > 0);

    std::reverse(result.begin(), result.end());
    return result;
}

unsigned int BaseConverter::base2dec(const std::string& baseDigits, const std::string& value)
{
    unsigned int numberBase = (unsigned int)baseDigits.length();
    unsigned int result = 0;
    for (size_t i = 0; i < value.length(); ++i)
    {
        result *= numberBase;
        int c = baseDigits.find(value[i]);
        if (c == std::string::npos)
            throw std::runtime_error("Invalid character");

        result += (unsigned int)c;
    }

    return result;
}
于 2011-01-19T22:13:01.787 に答える
-2

この関数を使用して、16 進文字を 10 進文字に変換できます。

void Hex2Char(const char* szHex, unsigned char& rch)
{
    rch = 0;
    for(int i=0; i<2; i++)
    {
        if(*(szHex + i) >='0' && *(szHex + i) <= '9')
            rch = (rch << 4) + (*(szHex + i) - '0');
        else if(*(szHex + i) >='A' && *(szHex + i) <= 'F')
            rch = (rch << 4) + (*(szHex + i) - 'A' + 10);
        else
            break;
    }
}    

それを使用して文字列を変換するよりも:

void HexStrToCharStr(const char* hexStr, unsigned char* decStr, int n)
{
    unsigned char d_ch;
    for(int i=0; i<n; i++)
    {
        Hex2Char(hexStr+2*i, d_ch);
        decStr[i] = d_ch;
    }
}
于 2011-01-19T14:33:57.927 に答える
-4

std::istringstream (sHex ) >> std::hex >> sDec;

于 2011-01-19T13:17:44.023 に答える