Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
858 views
in Technique[技术] by (71.8m points)

java - Decimal Conversion error

I am writing a program that will convert octal numbers to decimals. It compiles right and everything but there is something majorily wrong with my conversion code. It seems perfectly logic to me, however somehow when I run the program the conversions are wrong (i.e. 1 is converted to 36) can someone point out what is going wrong?

 public static int convert(int octal)
{
    int d1=0,d2=0,d3=0,d4=0,d5=0,d6=0,d7=0,d8=0;

    if(octal >=9999999){
    d8 = (octal-(octal%10000000));}
    if(octal >=999999){
    d7 = (octal-(octal%1000000));}
    if(octal >=99999){
    d6 = (octal-(octal%100000));}
    if(octal >=9999){
    d5 = (octal-(octal%10000));}
    if(octal >= 999){
    d4 = (octal-(octal%1000));}
    if(octal >= 99){
    d3 = (octal-(octal%100));}
    if(octal >= 9){
    d2 = (octal-(octal%10));}
    if(octal >= 0){
    d1 = (octal-(octal%1));}


    octal = (d8 * 8^7) + (d7 * 8^6) + (d6 * 8^5) + (d5 * 8^4) + (d4 * 8^3) + (d3 * 8^2) + (d2 * 8^1) + (d1 * 8^0);

    return octal;

}

this is just my convert method, my main method is what collects the int octal;

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is the problem:

8^7

The ^ operator doesn't do what you think it does. It does binary XOR...

However, I'd say that the whole design is distinctly suspect. An int value isn't "in" octal or any other base - it's just an integer. The number ten is the number ten, whether that's exressed as "10" in decimal, "A" in hex or "12" in octal. If you've got a sequence of characters which you want to parse as octal digits, the input to the method should be a String, not an int.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...