Here are the steps I’ve taken to get this error.
move_to_send = Integer.toString(b_id); // b_id >= 0 && b_id <= 8
// Send over socket
byte[] buf = move_to_send.getBytes();
DatagramPacket packet = new DatagramPacket(buf, buf.length, ADDRESS, opp_port);
socket.send(packet);
byte[] buf = new byte[GAME_DATA.BUF_SIZE];
DatagramPacket packet = new DatagramPacket(buf, GAME_DATA.BUF_SIZE);
socket.receive(packet);
byte[] data = packet.getData();
move_received = new String(data, "UTF-8");
// Error then occurs at this line
int move = Integer.parseInt(move_received);
I am simply trying to send an integer over a socket. Perhaps there is a better way? I would still like to know why this error occurs, because if I print the string move_received it is a single digit string
You should use
getBytes("UTF-8")instead.Didn’t see the comment that
trimsolved it, but still – adding some info.getBytesreturns the string in your system’s default charset, so this can cause your string to be garbled.However, since your
Stringonly contain digits – and digits are within theASCIIrange – this should not cause the problem you had – since most charsets likeISO-XXXXare one byte charsets and UTF-8 represents the ASCII characters using one byte as well.In any case, it is good practice for the future.