Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;

like image 596
user1714873 Avatar asked Dec 10 '25 15:12

user1714873


1 Answers

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.

like image 127
Jon Skeet Avatar answered Dec 12 '25 05:12

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!