[英]Convert a given binary string into Integer and Vice Versa in Java
I'm trying to convert a binary number in string into integer and vice versa .我正在尝试将字符串中的二进制数转换为整数,反之亦然。 For eg -
例如 -
Binary = 001 Integer - 1 I know i can do this like Binary = 001 Integer - 1 我知道我可以这样做
int decimal = 0;
int n = 0;
while(true){
if(binary == 0){
break;
} else {
int temp = binary%10;
decimal += temp*Math.pow(2, n);
binary = binary/10;
n++;
}
}
return decimal;
I want conversions between these two using some direct functions.我想使用一些直接函数在这两者之间进行转换。 Can anyone please help me.
谁能帮帮我吗。 Thankyou.
谢谢你。
So here is a simple answer for this.所以这里有一个简单的答案。 To Convert a Binary String let us say eg S= "001" to Integer use -
Integer.parse(S,2)
and to convert a Integer back to Binary String use- Integer.toBinaryString(num)
要转换二进制字符串,让我们说例如 S= "001" 使用整数 -
Integer.parse(S,2)
并将整数转换回二进制字符串使用 - Integer.toBinaryString(num)
Hope This Helps.希望这可以帮助。 Thankyou.
谢谢你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.