1

次のコードを使用して、16 進数を同等の 2 進数形式に変換するプログラムを作成しましたが、間違った結果が得られました。コードは次のとおりです。

public String convert(String num){
    String res="";
    int []hex={0000,0001,0010,0011,0100,0101,0110,0111,1000,1001,1010,1011,1100,1101,1110,1111};
    int i;
    char ch;
    for(i=0;i<num.length();i++)
    {
        ch=num.charAt(i);
        if(ch>='a' && ch<='f'){
            res+=hex[ch-97+10]+"";
        }
        else if(ch>='A' && ch<='F'){
            res+=hex[ch-65+10]+"";
        }
        else if(ch>='0' && ch<='9'){
            int d=ch-48;
            res+=hex[d]+"";
        }
    }
    return res;
}

サンプル入力を「12ae」として指定すると、対応する出力が「1810101110」として取得されます。入力フィールドに数字があり、すべての文字に対してのみ正常に機能する場合にのみ発生します(失敗します)。しかし、hex という名前の配列を String 型の配列に変更すると、正確な答えが得られます。

コンパイラが整数配列内の数値を何らかの形式の 8 進数として扱うためでしょうか、それとも他の理由でしょうか?

4

4 に答える 4

3

のようなあなたの数0010は8進数として解釈されます。書く0010ことは書くことと同じ8です。

を使用してバイナリ文字列に変換できますInteger.binaryString

于 2012-04-14T05:56:55.200 に答える
1

あなたは8進数で正しい方向に進んでいます。次の宣言:

int []hex={0000,0001,0010,0011,0100,0101,0110,0111,1000,...};

整数の配列を宣言します。つまり、次のようになります。

zero
one
eight
nine
sixty-four
sixty-five
seventy-two
seventy-three
one thousand

等々。これは明らかにあなたが望むものではありません。として宣言hexString[] hex、を使用する"0000","0001",...と、意図した答えが得られます。

于 2012-04-14T05:58:15.793 に答える
0

If you write this:

int []hex={0000,0001,0010,0011,0100,0101,0110,0111,1000,1001,1010,1011,1100,1101,1110,1111};

then Java ofcourse does not automatically know that these should be interpreted as binary numbers.

Integer literals that start with a 0 are interpreted as octal numbers. Integer literals starting with 1 to 9 are interpreted as decimal digits.

If you are using Java 7, you can use the new 0b syntax for binary numbers:

int[] hex ={ 0b0000, 0b0001, 0b0010, 0b0011, ..., 0b1111 };

Otherwise, use decimal or hexadecimal:

int[] hex = { 0, 1, 2, 3, 4, ..., 15 };
int[] hex = { 0x0, 0x1, 0x2, 0x3, ..., 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF };

But since these are just the numbers from 0 to 15, you don't even need the array at all: because hex[i] == i, you could just use i directly instead of hex[i].

于 2012-04-14T06:10:44.267 に答える
0

Numbers below eight are treated as octals, by the way if they didn't treated as octals 0001 would be changed to 1 and 0101 would be changed to 101, so you would loose required zeros in binary format.

By the way you can do this:

int value = Integer.parseInt(hex, 16);
String binary = Integer.toBinaryString(value);
于 2012-04-14T06:13:16.127 に答える