十进制转换为二进制 [英] Convert Decimal to Binary

查看:173
本文介绍了十进制转换为二进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个十进制数转换为二进制。我想创建的十进制数转换成二进制,然后调用从主要的方法来打印结果的方法,但我有一些麻烦。这是code我有这么远。托宾方法不能正常工作,我似乎无法找出什么我做错了。

I would like to convert a decimal number to binary. I want to create a method that converts the decimal number to binary and then call that method from Main to print the result, but I am having some trouble. This is the code I have so far. toBin method is not working properly and i cant seem to figure out what i am doing wrong.

我想了解我自己,所以任何帮助将是AP $ P $ java的pciated包括在必要的解释。我通过 http://knowledgeblackbelt.com 学习JAVA,这是演习之一。就像我说我不需要回答比我更想要一个例子,这个过程的解释,因为我似乎没有弄明白。感谢谁是真正帮助的人。

I am trying to learn java on my own so any help would be appreciated including explanations if necessary. I am learning JAVA through http://knowledgeblackbelt.com and this is one of the exercises. Like I said I do not need the answer more than I want an example and explanation of the process since I do not seem to figure it out. Thanks to the people who are really helping.

public class DecToBin {


public static void main(String[] args) {

    System.out.println(toBin(2));

}


public static int toBin(int Number){


    int result = 0;
    while(Number > 0){


        int mod = Number % 2;
        result = result * 1 + mod;

        Number /= 2;
    }

    return result;

}

}

推荐答案

希望这有助于:

/**
 * 
 * @author X
 *
 */
public class ConvertDecimal {

    public void convert(int decimal , int base)
    {
        int result = 0;
        int multiplier = 1;

          while(decimal > 0)
            {
              int residue = decimal % base;
              decimal     = decimal / base;
              result      = result + residue * multiplier;
              multiplier  = multiplier * 10;
            }

            System.out.println ("binary....." + result);
    }



    public static void main(String args[])
    {
        ConvertDecimal conv = new ConvertDecimal();
        conv.convert(128, 2);
    }

}

这篇关于十进制转换为二进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆