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