Wednesday, June 14, 2006

Java: Integer.toHexString()

So who out there would expect this code to work?

void write(PrintStream out, int x) throws IOException
{
  out.println(Integer.toHexString(x));
}
int read(BufferedStream in) throws IOException
{
  return Integer.parseInt(in.readLine(), 16);
}


I sure did. Nothing in the docs for toHexString() or parseInt(s, radix) indicates that it parseInt can't handle the output of toHexString(). How can this not be a bug? But sure enough, parseInt() can't read back in the result of toHexString() if the original value was negative (i.e. the high bit was set).

Why can't I just have unsigned int (and unsigned byte)? sigh...

1 Comments:

Anonymous RichB said...

This reminds me of a problem I noticed back in 2002 with System.Xml whereby writing out a document containing a decimal wrote it as nE-xx whereas XmlValidatingReader was unable to read this back in again.

1:31 PM  

Post a Comment

<< Home