0

我一直在尝试编写一个程序,将八进制转换为二进制,然后转换为十六进制,但问题是我得到了错误的答案。实际转换的代码如下:

    user_input=user_input.replace("0", "00");
    user_input=user_input.replace("1", "01");
    user_input=user_input.replace("2", "10");
    user_input=user_input.replace("3", "11");
    user_input=user_input.replace("4", "100");
    user_input=user_input.replace("5", "101");
    user_input=user_input.replace("6", "110");
    user_input=user_input.replace("7", "111");

    if (!(user_input.length()-1 % 4 ==0)){
        user_input = "00" + user_input; }


    user_input=user_input.replace("0000", "0");
    user_input=user_input.replace("0001", "1");
    user_input=user_input.replace("0010", "2");
    user_input=user_input.replace("0011", "3");
    user_input=user_input.replace("0100", "4");
    user_input=user_input.replace("0101", "5");
    user_input=user_input.replace("0110", "6");
    user_input=user_input.replace("0111", "7");
    user_input=user_input.replace("1000", "8");
    user_input=user_input.replace("1001", "9");
    user_input=user_input.replace("1010", "A");
    user_input=user_input.replace("1011", "B");
    user_input=user_input.replace("1100", "C");
    user_input=user_input.replace("1101", "D");
    user_input=user_input.replace("1110", "E");
    user_input=user_input.replace("1111", "F");

我的密钥使用数字 1057,它应该转换为 22F,但我得到的输出是 12F

知道我做错了什么吗?

4

2 回答 2

0

你可以考虑这个

int user_input_dec = Integer.parseInt(user_input,8);
String hex = Integer.toHexString(user_input_dec);
于 2013-10-14T16:58:44.703 回答
0

I see two problems:

  1. When converting 0-3 from octal to binary, you need that leading 0. Currently, your code changes octal 10 to binary 0100, which is incorrect (you've turned 8 into 4).
  2. When you parse from binary to hexadecimal, if you just do a replace, the result of parsing 0000 or 0001 may get parsed in a subsequent call. For example, if you have 00000010, it'll first change it to 00010, then 10 and stop, when it was supposed to be parsed into 2.

While it's possible to patch these up, @asantaballa is right, Integer.toHexString(Integer.parseInt(user_input, 8)) does the same thing as what you were trying to get your code to do.

于 2013-10-14T17:05:08.850 回答