Java基数转换程序给定值、其基数和新基数

标签 java math radix base-conversion

我试图弄清楚如何将特定基数中的任何值转换为不同基数中的相应表示形式。您将获得一个值、其基数以及该值需要在 .dat 文件的每一行中转换为的基数。

.dat 文件中的 3 行示例,其中一行中的第一个数字是值,后跟其所在的基数,然后是需要转换为的基数:

10 10 2

AB 16 10

345 6 4

我相信我已经弄清楚了,除了如何计算 16 和 18 等基数中的字母值。请帮忙:

public static void main( String args[] ) throws IOException
    {
        Scanner file = new Scanner(new File("baseConversion.dat"));
        //Keep looping while you can still read lines from the file
        while (file.hasNextLine())
        {
            //Read a line from the file -- read it as a string
            String line = file.nextLine();

            int firstSpace = line.indexOf(" ");
            int lastSpace = line.lastIndexOf(' ', line.length());
            String oldBase = line.substring(firstSpace + 1, lastSpace); 


            // Get the new base from the string
            int newBase = Integer.parseInt(line.substring(lastSpace + 1));


            //  Convert from the Old base to base 10
            int numberInBase10 = convertToTen(line.substring(0, firstSpace), Integer.parseInt(oldBase));
            System.out.println("Converted " + line.substring(0, firstSpace) + " from base " + oldBase + " to " +
            numberInBase10 + " in base 10\n");

            public static String convert(int numberInBase10, int base)
            {
            int quotient = numberInBase10 / newBase;
            int remainder = numberInBase10 % newBase;

            if(quotient == 0)
            {
                return Integer.toString(remainder);      
            }
            else
            {
                return convert(quotient, newBase) + Integer.toString(remainder);
            }
        }

        // DO THIS Print out results


        }
        file.close();
    }


    static int convertToTen(String num, int base)
    {

    int leng = num.length();
    int base10 = 0;
    int remainder = 0;
    int add = 0;


        for(int i = leng-1; i >=0; i--)
        {
            int intValueForC = 0;
            remainder = 0;

            char c = num.charAt(leng-i-1);
            if(!Character.isDigit(c))
            {
                intValueForC = c - 55;
            }
            else
            {
                intValueForC = c - 48;
            }
            add +=(intValueForC * Math.pow(base, i));

        }

        return add;
    }
}

最佳答案

你把这个变得过于复杂了(除非这是家庭作业并且不允许你使用库函数)。

String hex = "ABCDEF";
int decimal = Integer.parseInt(hex, 16);
String binary = Integer.toString(decimal, 2);

关于Java基数转换程序给定值、其基数和新基数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19370409/

相关文章:

java - org.hibernate.exception.SQLGrammarException : Could not execute JDBC batch update

java - 对多维数组进行快速排序

math - CGPoint 标量乘法 Swift

algorithm - 快速搜索平均变量列表

c++ - 在基类中调用派生类方法

java - 了解有关类的 FindBugs 警告不会覆盖父类(super class)中的等于

Java将哈希值转换为随机字符串

python - 对有界函数建模

java - 如何仅使用 while 和 if-else 循环转换为十六进制

frameworks - 为 Entity Framework 中的实体创建基类