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

标签 java string for-loop

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

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/

相关文章:

asp.net-mvc - 如何使用 Razor 引擎在 mvc5 中显示未排序的图像?

javascript - 如何从多维数组中迭代表中的数据

java - 在 iOS4 上部署 Java 应用程序是否有合法的、自动化的方法?

python - 如何分解多个组件中的字符串

java - 按轴表达式拆分 xpath 字符串

java - java 循环输出中不需要的重复

java.lang.NoSuchMethodError : org. apache.catalina.Context.addLifecycleListener

java - Servlet 安全过滤器

java - Eclipse PDE : Redeploy bundle to running equinox osgi framework

for-loop - 已声明但未在 for 循环中使用的变量