开发者

Java conversion from binary to octal

So I have this code for converting a binary to octal. I want to convert up to 64 bits of binary but it doesn't work.

What should I do?

String result=""; 
int i; 
long a[]=new long[100]; 
String input="11111111111111111111111111111111111111111111111";
i=0;
for(i=input.length();i>0;i-=3){
    a[i]=Long.parseLong(input.substring(i-3,i));
    if(a[i]==0) result+=开发者_运维技巧"0";
    else if(a[i] == 1) result += "1";
    else if(a[i]==10) result+="2";
    else if(a[i]==11) result+="3";
    else if(a[i]==100) result+="4";
    else if(a[i]==101) result+="5";
    else if(a[i]==110) result+="6";
    else if(a[i]==111) result+="7";
}
System.out.print(result);


The simple way is as follows:

long l = Long.parseLong(input, 2);
System.out.println(Long.toOctalString(l));

possibly with a try / catch to deal with a NumberFormatException that might be thrown by parseLong.


If the aim is to make your code (sort of) work, then here are some bugs that I can see:

  • You are building the result String backwards.
  • You don't need an array of longs. Just one long will do.
  • You are not dealing with the leftmost digits correctly. It looks like the last time around the loop will attempt to call substring with a negative 'from' argument ... and you'll get an exception.

Since this is HOMEWORK (I infer) ... I'm not going to tell you how to fix the code. The above hints are more than enough for you to do it yourself.


I haven't tested this, but it or something close should do the trick:

String result = Integer.toOctalString(Integer.parseInt(input, 2));


As an alternative to using the built-in functions like parseLong (which you seem to be using already, yet apparently are not allowed to) I'd suggest zero-padding the string to a multiple of three digits (use the modulus operator to determine the appropriate amount of padding), then iterating through each three digit section and doing a String-compare (similar to your existing long comparisons) to determine the appropriate output character. This solution would be hopelessly inefficient, but would at-least avoid using too many built in functions.


Try this code.

public class Octal {

    final static char[] octals = {
        '0', '1', '2', '3', '4', '5', '6', '7'
    };

    public static String toOctalString(long l) {
        long val = l;
        char[] buf = new char[64];
        int pos = 64;
        do {
            buf[--pos] = octals[(int) (val & 0x07)];
            val >>>= 3;
        } while (val != 0);
        return new String(buf, pos, (64 - pos));
    }

    public static long toDecimal(String binary) {
        // input validation and null checks are omitted
        char buf[] = binary.toCharArray();
        long l = 0;
        int shift = 0;
        for (int i = buf.length - 1; i >= 0; i--)
            l += ((buf[i] - '0') << shift++);

        return l;
    }

    public static void main(String[] args) {
            System.out.println(toOctalString(toDecimal("1000111010111")));
    }
}


If you don't want to use any built in methods available. Here is how i did this

public class BinaryToOctal {

public static void main(String[] args) {
    int counter = 0;
    String binary = "1101";
    StringBuilder reversedBinary = new StringBuilder(binary);
    String bin = String.valueOf(reversedBinary.reverse());

    StringBuilder octal = new StringBuilder();
    StringBuilder finalOctal = new StringBuilder();
    int length = binary.length();

    for (int i = 0; i < binary.length(); i++) {
        if (counter == 3) {
            finalOctal.append(convertOctal(octal.toString()));
            octal.delete(0, octal.length());
            counter = 0;
            length -= 3;
        }
        octal.append(bin.charAt(i));
        counter++;
        if (length==2 && counter==2){
            finalOctal.append(convertOctal(octal.toString()));
            octal.delete(0, octal.length());
        }

        if (length==1 && counter==1){
            finalOctal.append(convertOctal(octal.toString()));
            octal.delete(0, octal.length());
        }
    }
        System.out.println("Final octal number is: " + finalOctal.reverse());


}

public static String convertOctal(String num){
    switch(num) {
        case "000":
            return "0";
        case "001":
        case "01":
        case "1":
            return "1";
        case "010":
        case "10":
            return "2";
        case "011":
        case "11":
            return "3";
        case "100":
            return "4";
        case "101":
            return "5";
        case "110":
            return "6";
        case "111":
            return "111";
    }
    return "0";
}

}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜