Converting binary string to a hexadecimal string JAVA

前端 未结 7 865
陌清茗
陌清茗 2020-12-16 14:32

I want to convert my binary(which is in string) to hexadecimal string also, this is just a program fragment since this program is just a part of another bigger program:

7条回答
  •  春和景丽
    2020-12-16 15:18

     import java.util.*;
     public class BinaryToHexadecimal
     {
          public static void main()
          {
             Scanner sc=new Scanner(System.in);
             System.out.println("enter the binary number");
             double s=sc.nextDouble();
             int c=0;
             long s1=0;
             String z="";
             while(s>0)
             {
               s1=s1+(long)(Math.pow(2,c)*(long)(s%10));
               s=(long)s/10;
               c++;
             }
             while(s1>0)
             {
               long j=s1%16;
               if(j==10)
               {
                  z="A"+z;
               }
               else if(j==11)
               {
                  z="B"+z;
               }
               else if(j==12)
               {
                  z="C"+z;
               }
               else if(j==13)
               {
                  z="D"+z;
               }
               else if(j==14)
               {
                  z="E"+z;
               }
               else if(j==15)
               {
                  z="F"+z;
               }
               else
               {
                  z=j+z;
               }
               s1=s1/16;
          }
        System.out.println("The respective Hexadecimal number is : "+z);
       }
     }
    

提交回复
热议问题