在Java中从一个基数转换为另一个基数

现在,我正在尝试找到一种方法,在Java中将数字从一个基数转换为另一个基数,给出一个数字,数字所在的基数,以及转换为的基数。

public static void BaseConversion(String number, int base1, int base2){ //convert the number from one base to another } 

我找到了JavaScript的解决方案,我想知道是否可以在Java中执行类似的操作:

 function convertFromBaseToBase(str, fromBase, toBase){ var num = parseInt(str, fromBase); //convert from one base to another return num.toString(toBase); } 

你可以做到

 return Integer.toString(Integer.parseInt(number, base1), base2); 

所以使用Java中的函数签名:

 public String convertFromBaseToBase(String str, int fromBase, int toBase) { return Integer.toString(Integer.parseInt(str, fromBase), toBase); } 
 public class BaseToBaseConv { static String baseToBase(String num, int base1, int base2) { int no = convFrmBaseToDeci(num, base1); return convFrmDecToBase(no, base2); } static String convFrmDecToBase(int num, int base) { String res = ""; int rem; // Convert input number is given base by repeatedly // dividing it by base and taking remainder while (num > 0) { rem = num % base; if (base == 16) { if (rem == 10) res += 'A'; else if (rem == 11) res += 'B'; else if (rem == 12) res += 'C'; else if (rem == 13) res += 'D'; else if (rem == 14) res += 'E'; else if (rem == 15) res += 'F'; else res += rem; } else res += rem; num /= base; } // Reverse the result return new StringBuffer(res).reverse().toString(); } static int convFrmBaseToDeci(String num, int base) { if (base < 2 || (base > 10 && base != 16)) return -1; int val = 0; int power = 1; for (int i = num.length() - 1; i >= 0; i--) { int digit = digitToVal(num.charAt(i)); if (digit < 0 || digit >= base) return -1; // Decimal equivalent is str[len-1]*1 + // str[len-1]*base + str[len-1]*(base^2) + ... val += digit * power; power = power * base; } return val; } static int digitToVal(char c) { if (c >= '0' && c <= '9') return (int) c - '0'; else return (int) c - 'A' + 10; } public static void main(String [] args) { System.out.println(baseToBase("12345", 10, 2)); System.out.println(baseToBase("11000000111001", 2, 10)); System.out.println(baseToBase("ABC11", 16, 2)); System.out.println(baseToBase("10101011110000010001", 2, 16)); System.out.println(baseToBase("12322", 8, 16)); } } 

我相信这会奏效:

 long x = 10; int baseToConvertTo = 9; System.out.println(Long.toString(x, baseToConvertTo)); 

产量: 11

正如其他人所显示的那样, Integer.parseInt()可以为您完成此操作。 但是,如果您正在尝试自己构建转换器,则以下操作只需将数值转换为所需的基数即可。 注意,对于基数10以上的基数,你必须考虑alpha字符… IE 11-A,12-B等…

 public class NumberUtil { /** * This example is convoluted as in reality it just uses 'toString' to convert the number... * However, it displays the logic needed to make the conversion... * * To convert a number to a new radix, recursively return the remainder of the number * divided by the radix for each operation until zero. Then return the concatenated value in reverse. * * Example convert 9658 to base 2 * * 9658 / 2 = 4829 R 0 * 4829 / 2 = 2414 R 1 * 2414 / 2 = 1207 R 0 * 1207 / 2 = 603 R 1 * 603 / 2 = 301 R 1 * 301 / 2 = 150 R 1 * 150 / 2 = 75 R 0 * 75 / 2 = 37 R 1 * 37 / 2 = 18 R 1 * 18 / 2 = 9 R 0 * 9 / 2 = 4 R 1 * 4 / 2 = 2 R 0 * 2 / 2 = 1 R 0 * 1 / 2 = 0 R 1 * * Answer :: 10010110111010 * * @param number :: Integer number to convert. * @param radix :: Radix to convert to. * @return :: BigInteger of the number converted to the desired radix. */ static BigInteger convertBase( int number, int radix ) { List remainder = new ArrayList<>(); int count = 0; String result = ""; while( number != 0 ) { remainder.add( count, number % radix != 0 ? number % radix : 0 ); number /= radix; try { result += remainder.get( count ); } catch( NumberFormatException e ) { e.printStackTrace(); } } return new BigInteger( new StringBuffer( result ).reverse().toString() ); } public static void main( String[] args ) { System.out.println( convertBase( 9658, 2 ) ); } } 

考试:

 class Test1 { public static void main(String[] args) { String s1 = "10"; int n1 = Integer.parseInt(s1, 8); System.out.println(s1 + " is " + n1 + " in base10"); String s2 = Integer.toString(n1, 2); System.out.println(n1 + " is " + s2 + " in base2"); } } 

得到:

 C:\Temp>java Test1 10 is 8 in base10 8 is 1000 in base2 

使用Integer.parseIntInteger.toString

如果您可以确定相关数字分别在intlong范围内,则Integer.parseIntLong.parseLong的双参数版本将执行此操作。 如果你不能保证这一点,请使用java.math.BigInteger

 BigInteger bi = new BigInteger(number, base1); return bi.toString(base2); 

例如,这可以处理任意大的整数

 System.out.println( new BigInteger("12345678901234567890123456789", 10).toString(16)); // prints 27e41b3246bec9b16e398115 - too big to represent as a long 

由于您在js代码中提到了int ,因此在Integer类中有两种方法可供您查看:

 static int parseInt(String s, int radix) Parses the string argument as a signed integer in the radix specified by the second argument. 

 static String toString(int i, int radix) Returns a string representation of the first argument in the radix specified by the second argument. 

使用此代码

 import java.util.Scanner; // import scanner class public class BaseConverting { public static void main(String[] args) { Scanner input = new Scanner(System.in); //creating object from Scanner class String ans; System.out.println("Enter the decimal value need to convert !"); int decimal_value = input.nextInt(); //getting decimal value from user System.out.println("Select base \n Binary - b ;\n Octal- o ;\n HexaDecimal -h ;"); String choice = input.next(); //getting user needs Base type switch (choice) { case "b": ans = Integer.toString(decimal_value, 2); System.out.println("Binary value of " + decimal_value + " = " + ans); break; case "o": ans = Integer.toString(decimal_value, 8); System.out.println("Octal value of " + decimal_value + " = " + ans); break; case "h": ans = Integer.toString(decimal_value, 16); System.out.println("Hexa Decimal value of " + decimal_value + " = " + ans); break; } } } 

这个怎么样 ?

 public static void main(String[] args) { System.out.println(toDecimalBase("11111111", 2)); System.out.println(toDecimalBase("Ff", 16)); System.out.println(toDecimalBase("377", 8)); System.out.println(toDecimalBase("255", 10)); } private static int toDecimalBase(String number, int base) { int lenght = number.length(); int result = 0; for (int i = 0; i < lenght; i++) { // get char in a reverse order from the array int character = number.charAt(lenght - i - 1); // convert range [AF] to range of [0-6] if (character >= 'A' && character <= 'F') { character = character - 'A' + 10; } else if (character >= 'a' && character <= 'f') { character = character - 'a' + 10; } // Unicode to int else { character = Character.getNumericValue(character); } result += (Math.pow(base, i)) * character; } return result; }