用Java写一个字符串与整数(二进制)的转化
时间: 2024-05-22 19:15:51 浏览: 32
public class StringAndIntConversion {
// 将二进制字符串转化为整数
public static int binaryToInt(String binaryString) {
int result = 0;
for (int i = binaryString.length() - 1, j = 0; i >= 0; i--, j++) {
int bit = binaryString.charAt(i) - '0';
result += bit * Math.pow(2, j);
}
return result;
}
// 将整数转化为二进制字符串
public static String intToBinary(int num) {
StringBuilder binaryString = new StringBuilder();
while (num > 0) {
int bit = num % 2;
binaryString.append(bit);
num /= 2;
}
return binaryString.reverse().toString();
}
public static void main(String[] args) {
int num = 12;
String binaryString = intToBinary(num);
System.out.println(num + "的二进制字符串表示为:" + binaryString);
System.out.println(binaryString + "表示的整数为:" + binaryToInt(binaryString));
}
}
阅读全文