java将十进制转换为任何二进制位 [英] java-convert decimal to any binary bit

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

问题描述

我正在做一个将十进制数字转换为二进制的项目。但是我有一个问题,如何将任何输入的数字转换为二进制(我正在使用数组),这是我的代码:

I'm making a project of converting decimal number into binary. But I have a problem that how can I convert any entered number into binary (I'm using array), here is my code:

    public void Decimal2Binary(int a)
{
    int result []=new int[8];
    for (int i = 7;i >=0; i--,a/=2) {
        result[i]=a%2;
}

我只需要8位二进制结果就不需要它,我需要任何大小的东西。

I do not need it for just only 8-bit binary result, yet, I need it for any size.

推荐答案

您实际上并没有指定输出,但是就可以了。

You don't actually specify the output, but here goes.

假定未签名(看起来像您一样)。

assuming unsigned (as it looks like you have).

StringBuilder result = new StringBuilder();
while(a > 0) {
    result.append(a % 2);
    a = a / 2; // This will round down automatically. ;)
}

如果您需要处理负数,我会使用&运算符-您也可以使用>>进行除法,但我将优化保留在编译器中,以使源代码更具可读性。

If you need to handle negative numbers, I would do bitwise comparisons using the & operator - you could also use >> for the division, but I am leaving that optimisation for the compiler to keep the source more readable.

显然,您可以更改到任何形式的追加

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

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