Atom Feed SITE FEED   ADD TO GOOGLE READER

Hexed by converting ints to hex

Java's Integer class includes two methods for converting values into Strings. There's a general one:
    /**
* Converts the specified integer into a string representation based on the
* specified radix.
*/
public static String toString(int i, int radix) { ... }

Plus there's also methods for commonly used bases:
    /**
* Converts the specified integer into its hexadecimal string
* representation.
*/
public static String toHexString(int i) { ... }

/**
* Converts the specified integer into its octal string representation.
*/
public static String toOctalString(int i) { ... }

/**
* Converts the specified integer into its binary string representation.
*/
public static String toBinaryString(int i) { ... }

My expectation was that the first was simply a more general form. Given this assumption, I expected the following program to print the same three lines twice:
  public static void main(String... args) {
System.out.println(Integer.toHexString(0xCAFE));
System.out.println(Integer.toHexString(0xBABE));
System.out.println(Integer.toHexString(0xCAFEBABE));
System.out.println(Integer.toString(0xCAFE, 16));
System.out.println(Integer.toString(0xBABE, 16));
System.out.println(Integer.toString(0xCAFEBABE, 16));
}

But it turns out that negative numbers have slightly surprising results when combined with arbitrary bases. The program prints the following:
cafe
babe
cafebabe
cafe
babe
-35014542

If you're emitting hex or binary data, you probably should avoid toString(int value, int radix).
just look how it is implemented:

public static String toHexString(int i) {
return toUnsignedString(i, 4);
}

UnsignedString - that's the key