简体   繁体   English

如何将小数转换为较高的基数,反之亦然

[英]How to convert decimal to a higher base and vice versa

As a programming assignment for my java CSC class I have written the following code to convert a number and its base to a decimal number and then to a desired number and base. 作为我的Java CSC类的编程任务,我编写了以下代码,以将数字及其基数转换为十进制数字,然后转换为所需的数字和基数。

    public static int baseten(int number,int basein){
    int power = 0;
    int baseten = 0;
    while (number > 0) {
        int finalDigit = number % 10;
        int product = finalDigit*(int)Math.pow(basein, power);
        baseten += product;
        number = number / 10;
        power++;
    }
    return(baseten);
}
public static String convert (int decimal, int baseout){
    String result = "";
    while (decimal > 0){
        //if baseout
        int remainder = decimal % baseout;
        decimal = decimal / baseout;
        result = remainder + result;
    }
    return(result);
}

The question is how to convert a number to a base higher than ten within this code? 问题是如何在此代码中将数字转换为大于10的基数? I assume maybe a char[], but I'm not very good with arrays right now and can't imagine what that might look like. 我假设可能是char [],但是我现在对数组不是很满意,无法想象它会是什么样子。 I don't think I can use toString's or parseInt's. 我认为我不能使用toString或parseInt。 Any help would be appreciated. 任何帮助,将不胜感激。 Thanks in advance. 提前致谢。

You are almost there. 你快到了 What you could do is insert an if/else statement to determine whether the remainder is greater or equal to ten or not and act accordingly. 您可以做的是插入一个if / else语句,以确定余数是否大于或等于10,然后采取相应措施。 If it isn't, do what you're doing right now. 如果不是,请立即执行您的操作。 If it is, then you need to add a char to your string. 如果是,则需要在字符串中添加一个字符。 This char must be (remainder-10) + 65, since 65 is capital A on the ascii table and you need to know how many digits above ten remainder is and add that to A. This could be simplified to simply adding 55, but that is less readable in my opinion. 该字符必须为(remainder-10)+ 65,因为65在ascii表上是大写的A,并且您需要知道十位数以上是几位数并将其添加到A。这可以简化为简单地添加55,但是我认为可读性较差。 Then, just add that char to the string instead of adding the int. 然后,只需将该char添加到字符串中,而不是添加int。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM