Base 10 to base 2,8,16 conversion in java [duplicate]

空扰寡人 提交于 2019-11-28 22:11:36

for a decimal x (base 10) you can use respectively for binary, octal, hex conversion

Integer.toString(x, 2),

Integer.toString(x, 8)

Integer.toString(x, 16).

then to convert it back to decimal, respectively from binary, octal, hex conversion

Integer.valueOf(binary_value, 2)

Integer.valueOf(octal_value, 8)

Integer.valueOf(hex_value, 16)

in your code, change the following:

output = Integer.toString(input, 16) //replace 16 for hex, 8 for octal, 2 for binary 

use this

    if (choice == 1)

          output = Integer.toString(input, 2);

      else if (choice == 2)

          output = Integer.toString(input, 8);

    // if the user chooses choice #2, it will convert from base 10 to base of 8 
     else if (choice == 3)

          output = Integer.toString(input, 16);

  else

      System.out.println("invalid entry");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!