简体   繁体   English

如何从十六进制转换为十进制以及从十进制转换为二进制

[英]How to convert from Hexadecimal to Decimal and from Decimal to Binary

I would like how can I include the decimal result from the dance method to the light one. 我想如何将舞蹈方法的十进制结果包括到轻量方法中。 For example, in this program, if I input 5F, the decimal result would be 95. Well, I want that 95 to appear as a static int variable in the light method in order to be converted into a binary number. 例如,在此程序中,如果我输入5F,则十进制结果将为95。那么,我希望那95可以在light方法中显示为静态int变量,以便转换为二进制数。 It would be also very helpful if you could tell me how can I limit the hexadecimal number to only 2 figures. 如果您能告诉我如何将十六进制数限制为仅2个数字,这也将非常有帮助。 Thanks for reading! 谢谢阅读!

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class test2 {
public static void main(String args[]) throws Exception{
        DANCE(args);
        LIGHTS(args);

} }

      public static void DANCE(String[]args) throws Exception {
            BufferedReader reader= new BufferedReader(new InputStreamReader(System.in));
            System.out.println("Enter hex no:"+"");
            int no= Integer.parseInt(reader.readLine(), 16);
            System.out.println("Decimal no:"+no);

} }

       public static void LIGHTS(String a[]){
                System.out.println("Binary representation: ");
                System.out.println(Integer.toBinaryString(no));
      }
    }

Welcome to Stackoverflow, 欢迎使用Stackoverflow,

if you want to convert a hexadecimal value to a plain integer you can use: 如果要将十六进制值转换为纯整数,可以使用:

int i = Integer.parseInt("5F", 16);
System.out.println(i); // will print 95

And if you want your plain integer to be converted into a binary String you could use: 如果您希望将纯整数转换为二进制字符串,则可以使用:

String j = Integer.toBinaryString(i); // from the above variable j which contains 95
System.out.println(j); // will print 1011111

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

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