思路:对十进制的数进行除2取余法:
/** * 讲10 进制转化为二进制 * @param de :待转换的十进制 * @return :转换后的二进制(string) */
public static String Decimal2Binary(int de){
String numstr = "";
while (de>0){
int res = de%2; //除2 取余数作为二进制数
numstr = res + numstr;
de = de/2;
}
return numstr;
}
思路:对二进制从后往前数第i位上的数进行乘以2的i-1 次方;
/** * 将二进制转换为10进制 * @param bi :待转换的二进制 * @return */
public static Integer Biannary2Decimal(int bi){
String binStr = bi+"";
Integer sum = 0;
int len = binStr.length();
for (int i=1;i<=len;i++){
//第i位 的数字为:
int dt = Integer.parseInt(binStr.substring(i-1,i));
sum+=(int)Math.pow(2,len-i)*dt;
}
return sum;
}
完整代码:
import java.awt.*;
import java.util.Scanner;
/** * Created by chen on 2020/7/12. */
public class Test {
public static void main(String args[]) {
//testD2B();
//testB2D();
}
/** * 讲10 进制转化为二进制 * @param de * @return */
public static String Decimal2Binary(int de){
String numstr = "";
while (de>0){
int res = de%2; //除2 取余数作为二进制数
numstr = res + numstr;
de = de/2;
}
return numstr;
}
/** * 将二进制转换为10进制 * @param bi * @return */
public static Integer Biannary2Decimal(int bi){
String binStr = bi+"";
Integer sum = 0;
int len = binStr.length();
for (int i=1;i<=len;i++){
//第i位 的数字为:
int dt = Integer.parseInt(binStr.substring(i-1,i));
sum+=(int)Math.pow(2,len-i)*dt;
}
return sum;
}
public static void testB2D(){
while (true){
System.out.println("Pleace input a Binary num:");
Scanner sc = new Scanner(System.in);
int binary = sc.nextInt();
int out = Biannary2Decimal(binary);
System.out.println("The Decimal num is :" + out);
System.out.println("输入0 结束,输入1 继续");
sc = new Scanner(System.in);
if (sc.nextInt()==0){
break;
}
}
}
public static void testD2B(){
while (true) {
System.out.println("Pleace input a int Decimal num:");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
String numofBinary = Decimal2Binary(num);
System.out.println("The Binary num is :" + numofBinary);
System.out.println("输入0 结束,输入1继续");
sc = new Scanner(System.in);
if (sc.nextInt() == 0) {
break;
}
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/180781.html原文链接:https://javaforall.cn
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有