进制转换

十进制转八进制

最近水题的时候水到一个题目,题目如下:

思路很简单,就是将对应的数字取余再除以8,如此往复。

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        while(scanner.hasNextInt()) {
            decimalToOctal(scanner.nextInt());
        }
    }

    private static void decimalToOctal(int num) {

        int radix = 8; //8进制
        int result=0;
        int base = 1;
        while(num!=0)    
        {
            int temp = num%radix;
            temp = temp*base;
            base *= 10;
            result += temp;
            num/=radix;
        }
        System.out.println(result);
    }

}

通用解法

上面这种解法并不通用,只能转换为8进制,而且无法应付num是负数的情况比如-8, 其八进制根据原码、补码的规则应该是FFFFFFF8。后来想起java.lang.Integer中也有进制转换的函数,想看看JDK是如何实现进制转换的。 就这样发现了一个通用解法。

 

 /**
     * All possible chars for representing a number as a String
     */
    final static char[] digits = {
        '0' , '1' , '2' , '3' , '4' , '5' ,
        '6' , '7' , '8' , '9' , 'a' , 'b' ,
        'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
        'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
        'o' , 'p' , 'q' , 'r' , 's' , 't' ,
        'u' , 'v' , 'w' , 'x' , 'y' , 'z'
    };

    /**
     * Returns a string representation of the first argument in the
     * radix specified by the second argument.
     *
     * <p>If the radix is smaller than {@code Character.MIN_RADIX}
     * or larger than {@code Character.MAX_RADIX}, then the radix
     * {@code 10} is used instead.
     *
     * <p>If the first argument is negative, the first element of the
     * result is the ASCII minus character {@code '-'}
     * ({@code '\u005Cu002D'}). If the first argument is not
     * negative, no sign character appears in the result.
     *
     * <p>The remaining characters of the result represent the magnitude
     * of the first argument. If the magnitude is zero, it is
     * represented by a single zero character {@code '0'}
     * ({@code '\u005Cu0030'}); otherwise, the first character of
     * the representation of the magnitude will not be the zero
     * character.  The following ASCII characters are used as digits:
     *
     * <blockquote>
     *   {@code 0123456789abcdefghijklmnopqrstuvwxyz}
     * </blockquote>
     *
     * These are {@code '\u005Cu0030'} through
     * {@code '\u005Cu0039'} and {@code '\u005Cu0061'} through
     * {@code '\u005Cu007A'}. If {@code radix} is
     * <var>N</var>, then the first <var>N</var> of these characters
     * are used as radix-<var>N</var> digits in the order shown. Thus,
     * the digits for hexadecimal (radix 16) are
     * {@code 0123456789abcdef}. If uppercase letters are
     * desired, the {@link java.lang.String#toUpperCase()} method may
     * be called on the result:
     *
     * <blockquote>
     *  {@code Integer.toString(n, 16).toUpperCase()}
     * </blockquote>
     *
     * @param   i       an integer to be converted to a string.
     * @param   radix   the radix to use in the string representation.
     * @return  a string representation of the argument in the specified radix.
     * @see     java.lang.Character#MAX_RADIX
     * @see     java.lang.Character#MIN_RADIX
     */
    public static String toString(int i, int radix) {
        // 参数验证,如果不和要求则转为十进制 //
        if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
            radix = 10;

        // 如果是转为十进制就直接toString() //
        /* Use the faster version */
        if (radix == 10) {
            return toString(i);
        }

        // 开始转换 //
        char buf[] = new char[33]; //用于构造最后的结果字符串
        boolean negative = (i < 0);
        int charPos = 32;

        if (!negative) { //将正数转为负数,方便后面正负数统一处理
            i = -i;
        }

        while (i <= -radix) {
            buf[charPos--] = digits[-(i % radix)];
            i = i / radix;
        }
        buf[charPos] = digits[-i];

        if (negative) {
            buf[--charPos] = '-';
        }

        return new String(buf, charPos, (33 - charPos));
    }

 

posted @ 2017-05-01 10:30  付大石  阅读(646)  评论(0编辑  收藏  举报