首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java base转换程序给定值、它的base和new base

Java base转换程序给定值、它的base和new base
EN

Stack Overflow用户
提问于 2013-10-15 06:37:22
回答 1查看 3.8K关注 0票数 0

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

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

10 10 2

AB 16 10

345 6 4

我相信我已经弄明白了,除了如何计算16和18等基数的字母值。请帮助:

代码语言:javascript
复制
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;
    }
}
EN

回答 1

Stack Overflow用户

发布于 2013-10-15 06:47:22

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

代码语言:javascript
复制
String hex = "ABCDEF";
int decimal = Integer.parseInt(hex, 16);
String binary = Integer.toString(decimal, 2);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19370409

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档