gpt4 book ai didi

Java 八进制到二进制的转换(没有预定义的方法)

转载 作者:行者123 更新时间:2023-11-29 03:02:34 25 4
gpt4 key购买 nike

我正在尝试创建一个将八进制值转换为二进制值的计算器。

temp = txt.getText();
temptemp = "";
if (prev == 3) {
for (int i = 0; i < temp.length() - 1; i++) {
if (temp.charAt(i) == '1') {
temptemp = temptemp + "000";
} else if (temp.charAt(i) == '2') {
temptemp = temptemp + "001";
} else if (temp.charAt(i) == '3') {
temptemp = temptemp + "010";
} else if (temp.charAt(i) == '4') {
temptemp = temptemp + "011";
} else if (temp.charAt(i) == '5') {
temptemp = temptemp + "100";
} else if (temp.charAt(i) == '6') {
temptemp = temptemp + "101";
} else if (temp.charAt(i) == '7') {
temptemp = temptemp + "111";
}
}
temp = temptemp;
txt.setText(temp);

我的循环语句有什么问题?请帮忙。谢谢:)

编辑:

我现在知道问题所在了。感谢大家的评论和回答。我增加了 1 个。我应该从 == 0 开始。对不起,谢谢你:)

最佳答案

您可以通过执行一些按位运算来跳过这一长串显式案例:

StringBuilder sb = new StringBuilder(3 * temp.length());
for (int i = 0; i < temp.length(); i++) {
// + check that the character is actually an octal digit.
int digit = Character.digit(temp.charAt(i), 10);
for (int b = 2; b >= 0; --b) {
sb.append(Character.forDigit((digit >> b) & 0x1, 10));
}
}

关于Java 八进制到二进制的转换(没有预定义的方法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33934307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com