0

「19485」、「10011010」、「AF294EC」などの文字列を処理するこのコードがあります...

long long toDecimalFromString(string value, Format format){
    long long dec = 0;
    for (int i = value.size() - 1; i >= 0; i--) {
        char ch = value.at(i);
        int val = int(ch);
        if (ch >= '0' && ch <= '9') {
            val = val - 48;
        } else {
            val = val - 55;
        }
        dec = dec + val * (long long)(pow((int) format, (value.size() - 1) - i));
    }
    return dec;
}

このコードは、2 の補数でないすべての値に対して機能します。10 進数で負の数になるはずの 16 進文字列を渡すと、正しい結果が得られません。

4

2 に答える 2

1

マイナス記号を処理しないと、それ自体は処理されません。それを確認し、見たことを覚えておいてください。次に、最後に'-'、最初の文字として a を見た場合は、結果を否定します。

その他のポイント:

  • を使用する必要はありません (または使用したくありません) 。毎回実行するpowだけ です。results = format * results + digit
  • 入力を検証して、取得した数字がベースで有効であることを確認する必要があります (および、他の奇妙な文字がないことを確認します)。
  • オーバーフローもチェックする必要があります。
  • 文字チェックにはisdigitand isalpha(またはislowerand ) を使用する必要があります。isupper
  • 文字コードから数字値への変換には、eg val -= '0'( ではなく) を使用する必要があります。48
  • 個々の文字を読み取るには、 では[i]なくを使用する必要があります。at(i)通常の開発オプションでコンパイルすると、エラーが発生した場合に、例外ではなくクラッシュが発生します。
  • ただし、文字列を処理するには、おそらくインデックスではなくイテレータを使用する必要があります。それははるかに慣用的です。
  • ほとんどの場合、アルファベットの大文字と小文字の両方を受け入れる必要があり、おそらく先頭の空白もスキップする必要があります。

技術的には、アルファベット文字が順番に隣接しているという保証もありません。'A'-'F'実際には、範囲内の文字(または )を当てにできると思いますが、'a'-'f'文字を数字に変換する最も確実な方法は、テーブル ルックアップを使用することです。

于 2013-09-25T16:35:28.067 に答える
0

You need to know whether the specified number is to be interpreted as signed or unsigned (in other words, is "ffffffff" -1 or 4294967295?). If signed, then to detect a negative number test the most-significant bit. If ms bit is set, then after converting the number as you do (generating an unsigned value) take the 1's complement (bitwise negate it then add 1).

Note: to test the ms bit you can't just test the leading character. If the number is signed, is "ff" supposed to be -1 or 255?. You need to know the size of the expected result (if 32 bits and signed, then "ffffffff" is negative, or -1. But if 64 bits and signed, "ffffffff' is positive, or 4294967295). Thus there is more than one right answer for the example "ffffffff".

Instead of testing ms bit you could just test if unsigned result is greater than the "midway point" of the result range (for example 2^31 -1 for 32-bit numbers).

于 2013-09-25T16:56:31.673 に答える