Java十进制转二进制
闲着没事写了个简单的十进制转二进制的算法,很简单,个人记录一下,不妥之处请指正。
public static String toBinaryString(int j) { if (j < 0) {
throw new NumberFormatException("不支持负数");
}
double i = (double) j;
StringBuilder sb = new StringBuilder();
while (true) {
if (i % 2 == 0)
sb.append("0");
else
sb.append("1");
int result = (int) (i / 2);
if (result == 1) {
sb.append("1");
break;
}
i = (double) result;
}
char[] chars = sb.toString().toCharArray();
int len = chars.length - 1;
for (int a = 0; a <= len; a++) {
char c = chars[a];
char d = chars[len];
chars[a] = d;
chars[len] = c;
len--;
}
return new String(chars);
}
以上是 Java十进制转二进制 的全部内容, 来源链接: utcz.com/z/390071.html