Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting from decimal to hexadecimal

Tags:

java

algorithm

I have written a java program that is supposed to convert decimals from 1 to 256 to hexadecimal but the problem comes when i try decimals above 256 after which i start getting incorrect results. Here is a my code:

public class Conversion {

public static void main(String[] args) {

    System.out.printf("%s%14s", "Decimal", "Hexadecimal");

    for(int i = 1; i <= 300; i++) {
        System.out.printf("%7d          ", i);
        decimalToHex(i);
        System.out.println();
    }

}

private static void decimalToHex(int decimal) {
    int count;
    if(decimal >= 256) {
        count = 2;
    } else {
        count = 1;
    }
    for (int i = 1; i <= count; i++) {
        if(decimal >= 256) {
            returnHex(decimal / 256);
            decimal %= 256;
        }

        if(decimal >= 16) {
            returnHex(decimal / 16);
            decimal %= 16;
        }

        returnHex(decimal);

        decimal /= 16;
    }
}

private static void returnHex(int number) {
    switch(number) {
        case 15:
            System.out.print("F");
            break;
        case 14:
            System.out.print("E");
            break;
        case 13:
            System.out.print("D");
            break;
        case 12:
            System.out.print("C");
            break;
        case 11:
            System.out.print("B");
            break;
        case 10:
            System.out.print("A");
            break;
        default:
            System.out.printf("%d", number);
            break;
    }
}

}

This is the sample of the results that i got:

254              FE
255              FF
256              100
257              111
264              199
266              1AA
271              1FF
272              1100
273              1111

Note: I have just started learning java so keep it simple if you can. Thank you

like image 493
kellymandem Avatar asked Nov 04 '14 14:11

kellymandem


People also ask

What is Ffffffff in hexadecimal?

Hex value FFFFFFFF represents the integer value -1.


1 Answers

You simply forgot to print out the zero values in case the decimal is less than the compare value. When explicitly printing out those zeroes, you also do not need the count variable anymore:

private static void decimalToHex(int decimal) {
    if (decimal >= 256) {
        returnHex(decimal / 256);
        decimal %= 256;
    } else {
        System.out.print("0");
    }
    if (decimal >= 16) {
        returnHex(decimal / 16);
        decimal %= 16;
    } else {
        System.out.print("0");
    }
    returnHex(decimal);
    decimal /= 16;
}

Of course, this also changes the output of the small values. It prints 000, 001, ...

like image 121
Seelenvirtuose Avatar answered Oct 06 '22 06:10

Seelenvirtuose