二进制转换器java,二进制到十进制Java转换器

我正在创建一个代码,允许您将二进制数转换为十进制数,反之亦然.我已经创建了一个将十进制转换为二进制的代码,但无法研究如何实现二进制到十进制的方面.

我的十进制到二进制的代码如下:

import java.util.*;

public class decimalToBinaryTest

{

public static void main (String [] args)

{

int n;

Scanner in = new Scanner(System.in);

System.out.println("Enter a positive interger");

n=in.nextInt();

if(n < 0)

{

System.out.println("Not a positive interger");

}

else

{

System.out.print("Convert to binary is: ");

binaryform(n);

}

}

private static Object binaryform(int number)

{

int remainder;

if(number <= 1)

{

System.out.print(number);

return " ";

}

remainder= number % 2;

binaryform(number >> 1);

System.out.print(remainder);

{

return " ";

}

}

}

二进制到十进制代码如何工作的解释也会有所帮助.

我已经尝试了最低有效数字* 1的方法,然后是下一个最低* 1 * 2然后* 1 * 2 * 2,但无法使其工作.

谢谢@korhner我用你的数字系统和数组和if语句.

这是我的工作代码:

import java.util.*;

public class binaryToDecimalConvertor

{

public static void main (String [] args)

{

int [] positionNumsArr= {1,2,4,8,16,32,64,128};

int[] numberSplit = new int [8];

Scanner scanNum = new Scanner(System.in);

int count1=0;

int decimalValue=0;

System.out.println("Please enter a positive binary number.(Only 1s and 0s)");

int number = scanNum.nextInt();

while (number > 0)

{

numberSplit[count1]=( number % 10);

if(numberSplit[count1]!=1 && numberSplit[count1] !=0)

{

System.out.println("Was not made of only \"1\" or \"0\" The program will now restart");

main(null);

}

count1++;

number = number / 10;

}

for(int count2 = 0;count2<8;count2++)

{

if(numberSplit[count2]==1)

{

decimalValue=decimalValue+positionNumsArr[count2];

}

}

System.out.print(decimalValue);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值