Search code examples
javastringdatagramparseint

NumberFormatException for valid number String


I'm making a program that needs to receive data over the internet. It's doing so using DatagramSockets and receiving DatagramPackets. This all works fine, and the byte array it receives is the exact one I would expect.

However, when I try to convert the byte array to a string, and subsequently to an integer, very strange things happen.

Running the code below gives a NumberFormatException on the parseInt line:

String length = new String(data, 1, data.length-1);
System.out.println("length = "+length);
size = Integer.parseInt(length);
System.out.println("size = "+size);

However, when I inspect the contents of data, I see that it just contains 55,52,49,56,53,0,0,0,0,0,0,0,0,0,0,0,0, which is fine, it's the string "74185". This throws the exception though.

When I hardcode "74185" as the length string, everything works nicely.

What could be going wrong here?


Solution

  • Your string contains embedded \0 characters. In Java, they are part of the string, other than in C.

    So you first need to find the first occurrence of \0 in the string and then take the substring up to that position.