Converting 32 bit hexadecimals to decimal in java
for an assignment I have to write a program that will take in an 8 character string(hexadecimal) and then convert it to base 10. I am not allowed to use any outside classes to do this. I'm pretty sure I have it working properly... for positive numbers only. My problem is how to show negative numbers. an example is that FFFFFFFA should print out as -6 This is my code so far
package hexconverter;
import java.util.*;
/**
*
* @author Steven
*/
public class Main {
Scanner scanner = new Scanner(System.in);
public void doWork() {
System.err.println("Please enter the internal representation: ");
String hex;
hex = scanner.next();
hex = hex.toUpperCase();
long count = 1;
long ans = 0;
for (int i = 7; i >= 0; i--) {
Character c = hex.charAt(i);
if (c != '1' && c != '2' && c != '3' && c != '4' && c != '5' && c != '6' && c != '7' && c != '8' && c != '9') {
int num = fixLetters(c);
ans = ans + (num * count);
count = count * 16;
} else {
String s = c.toString(c);
long num = Integer.parseInt(s);
ans = ans + (num * count);
count = count * 16;
}
}
if (ans > 2147483647) {
System.out.println("is negative");
} else {
System.out.println(ans);
}
}
public int fixLetters(Character c) {
if (c.equals('A')) {
return 10;
} else if (c.equals('B')) {
return 11;
} else if (c.equals('C')) {
return 12;
} else if (c.equals('D')) {
return 13;
} else if (c.equals('E')) {
return 14;
} else if (c.equals('F')) {
return 15;
} else {
return 0;
}
}
public static void main(String[] args) {
// TODO code application logic here
Main a = new Main();
a.doWork();
}
}
I think my test for a negative integer is correct... since that is the highest value 32 bits can hold, anything over that will be an overflow so that means it should be negative. 开发者_开发技巧From here I have no idea how to go about this. Any pointers or tips would be greatly appreciated. If there is no way to do it mathematically I feel like I am going to have to convert the hex into binary and then perform twos complements on it, but again I dont know where to start.
Thanks in advance
If the number is negative (> 2147483647) in your code, just subtract 2^32
(4294967296) from it. Then print it out.
if (ans > 2147483647) {
System.out.println(ans - 4294967296L);
} else {
System.out.println(ans);
}
In 32-bit 2's complement binary representation, the value of a negative is exactly 2 ^ 32 less than the value of the same bit pattern in unsigned representation. You have already identified that the number might be negative; all that's left to do is subtract 2 ^ 32.
Of course, 2 ^ 32 (4294967296 in decimal, or 0x100000000 in hex) is a value that can't be represented by Java's "int" type, so you'll need to use a "long":
if (ans > 2147483647) {
// System.out.println("is negative");
ans = ans - 0x100000000L;
System.out.println(ans);
} else {
精彩评论