简体   繁体   English

Java从十进制转换为8位二进制

[英]Java convert from decimal to 8-bit binary

i wrote simple java code to convert from decimal to 8-bit binary: sorry for this stupid question我写了简单的 java 代码来从十进制转换为 8 位二进制:抱歉这个愚蠢的问题

 1       int dec=1;
 2       String result="";
 3       String reverse = "";
 4       while(dec!=0)
 5           {
 6               result+=dec%2;
 7               dec=dec/2;    
 8           }            
 9       //8-Bit Binary 
 10       System.out.println("dec length is :"+result.length());

// int j=8-result.length(); // int j=8-result.length(); // for(int i=0;i // for(int i=0;i

 11        for(int i=0;i<(8-result.length());i++)
 12       {
 13            result+=0;
 14            System.out.println("*");
 15       }
 16       System.out.println("8-Bit before reverse:"+result); 
 17       for(int i = result.length() - 1; i >= 0; i--)
 18        {
 19           reverse = reverse + result.charAt(i);
 20        }
 21       System.out.println("8-bit representation:"+reverse);

the result was : dec length is :1 * * * * 8-Bit before reverse:10000 8-bit representation:00001结果是:dec 长度为:1 * * * * 反转前的 8 位:10000 8 位表示:00001

but when i remove line 13 (result+=0;) the compiler print 7 asterisk(*), what is the reason for that?但是当我删除第 13 行(result+=0;)时,编译器会打印 7 个星号(*),这是什么原因? length of result will update every time结果的长度每次都会更新

It is because of the confition of your for loop: 这是因为您的for循环没用:

for(int i=0;i<(8-result.length());i++)

And the action in it: 以及其中的动作:

result+=0;

Increasing the length of result makes the result of 8-result.length() smaller (8 - 2 = 6, 8 - 3 = 5 ...), hence the loop being executed less times. 增加结果的长度会使8-result.length()的结果较小(8-2 = 6,8-3 = 5 ...),因此循环执行的次数更少。

Because result is a String . 因为 resultString Adding an int zero to a String , like this String添加一个int零,像这样

result+=0;

invokes the same behavior as 调用与以下行为相同的行为

result+=String.valueOf(0);
//Decimal to Binary Conversion
            int dec=1;
            String result= "00000000";
            int i=result.length()-1;
            while(dec!=0)
            {
              char a[]=result.toCharArray();
              a[i--]= String.valueOf(dec%2).charAt(0);
              result=new String(a);
              dec=dec/2;  

            }
            System.out.println(result);

You can try this simple code too: 您也可以尝试以下简单代码:

void intToBinary(int a) {
        String temp = Integer.toBinaryString(a);
        while(temp.length() !=8){
            temp = "0"+temp;
        }
        System.out.println(temp);
    }

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

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