Decimal to Hexadecimal Converter in Java

后端 未结 13 2399
有刺的猬
有刺的猬 2020-12-03 13:57

I have a homework assignment where I need to do three-way conversion between decimal, binary and hexadecimal. The function I need help with is converting a decimal into a he

13条回答
  •  误落风尘
    2020-12-03 14:44

    Consider dec2m method below for conversion from dec to hex, oct or bin.

    Sample output is

    28 dec == 11100 bin 28 dec == 34 oct 28 dec == 1C hex

    public class Conversion {
        public static void main(String[] argv) {
            int x = 28;                           // sample number
            if (argv.length > 0)
                x = Integer.parseInt(argv[0]);    // number from command line
    
            System.out.printf("%d dec == %s bin\n", i, dec2m(x, 2));
            System.out.printf("%d dec == %s oct\n", i, dec2m(x, 8));
            System.out.printf("%d dec == %s hex\n", i, dec2m(x, 16));
        }
    
        static String dec2m(int N, int m) {
            String s = "";
            for (int n = N; n > 0; n /= m) {
                int r = n % m;
                s = r < 10 ? r + s : (char) ('A' - 10 + r) + s;
            }
            return s;
        }
    }
    

提交回复
热议问题