Hexadecimal conversion decimal (JAVA version)

Keywords: Java

The way to solve the problem is: convert hexadecimal number to binary number, and then binary number to octal number. In the conversion of hexadecimal to octal, we can use the "&" operation symbol in JAVA. A hexadecimal number can be expressed as four binary numbers. By using "&" we can move a hexadecimal number to the right four times to get four binary numbers. When binary numbers are converted to octal numbers, an octal number can be expressed as a three bit binary number, so three bits in one can be used. One thing we should pay attention to in this question is to ensure that the number of digits to be converted into binary is a multiple of 3.

import java.util.*;
public class Main {
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        String a[]=new String[n];
        String b[]=new String[n];
        for(int i=0;i<n;i++)
        {
            a[i]=sc.next();
            b[i]="";
        }
        for(int i=0;i<n;i++)
        {
            b[i]=hexToOctal(a[i]);
            System.out.println(b[i]);
        }
    }
    static String hexToOctal(String str)
    {
        String s=to2(str);
        String s1=add0(s);
        return to8(s1);
    }
    static String to2(String str)
    {
        char chs[]= {'0','1'};
        String s=new String("0123456789ABCDEF");
        char c1[]=str.toCharArray();
        int pos=str.length()*4;
        char c2[]=new char[pos];
        for(int i=str.length()-1;i>=0;i--)
        {
            int temp=s.indexOf(c1[i]);
            for(int j=0;j<4;j++)
            {
                c2[--pos]=chs[temp&1];
                temp=temp>>>1;
            }
        }
        return new String(c2);
    }
    static String add0(String str)
    {
        String s=str.substring(str.indexOf('1'));
        int len=s.length();
        if(len%3==0)
            return s;
        else if(len%3==1)
            return "00"+s;
        else
            return "0"+s;
    }
    static String to8(String str)
    {
        HashMap<String,Character> map=new HashMap<String, Character>();
        map.put("000", '0');
        map.put("001", '1');
        map.put("010", '2');
        map.put("011", '3');
        map.put("100", '4');
        map.put("101", '5');
        map.put("110", '6');
        map.put("111", '7');
        int pos=str.length()/3;
        char c1[]=new char[pos];
        for(int i=str.length();i>0;i-=3)
        {
            String s=str.substring(i-3, i);
            c1[--pos]=map.get(s);
        }
        return new String(c1);
    }
    

}

Posted by Nadzree on Mon, 11 Nov 2019 07:12:54 -0800