加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

二进制&十进制相互转换

发布时间:2020-12-14 05:13:37 所属栏目:大数据 来源:网络整理
导读:public class Test {?? ?public static void main(String[] args) {?? ??? ?System.out.println(addBinary("1010","1011"));?? ?}?? ??? ?public static int addBinary(String a,String b) {??????? int aa = Integer.valueOf(a);??????? int bb = Integer.v

public class Test {?? ?public static void main(String[] args) {?? ??? ?System.out.println(addBinary("1010","1011"));?? ?}?? ??? ?public static int addBinary(String a,String b) {??????? int aa = Integer.valueOf(a);??????? int bb = Integer.valueOf(b);??????? aa = toDecimal(aa);??????? bb = toDecimal(bb);??????? int sum = aa + bb;??????? return toBinary(sum);??? }?? ?public static int toDecimal(int num) {?? ??? ?int res = 0;?? ??? ?int p = 0;?? ??? ?while(true) {?? ??? ??? ?if(num == 0) {?? ??? ??? ??? ?break;?? ??? ??? ?} else {?? ??? ??? ??? ?int tmp = num % 10;//从右向左、逐步增加?? ??? ??? ??? ?res += tmp * Math.pow(2,p++);?? ??? ??? ??? ?num /= 10;?? ??? ??? ?}?? ??? ?}?? ??? ?return res;?? ?}?? ??? ?public static int toBinary(int num) {?? ??? ?StringBuilder sb = new StringBuilder();?? ??? ?while(num != 0) {?? ??? ??? ?int n = num % 2;?? ??? ??? ?num /= 2;?? ??? ??? ?sb.append(n);?? ??? ?}?? ??? ?return Integer.parseInt(sb.reverse().toString());?? ?}}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读