sending negative bytes with tcp

I am sending a byte by a TCP connection, when I send a single negative number (like -30 in this example) I get three bytes:

Client Side:

PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
out.write((byte)-30);
out.flush();
out.close();

Server Side:

is = new DataInputStream(clientSocket.getInputStream());
is.readFully(bbb);
for (int i=0;i<bbb.length;i++)
    System.out.println(i+":"+bbb[i]);

what i get is:

0:-17
1:-65
2:-94

but I sent just -30

Jon Skeet
people
quotationmark

You're using a writer, and you're calling Writer.write(int):

Writes a single character. The character to be written is contained in the 16 low-order bits of the given integer value; the 16 high-order bits are ignored.

So you've got an conversion to int, then the bottom 16 bits of that int are taken. So you're actually writing Unicode character 65506 (U+FFE2), in your platform default encoding (which appears to be UTF-8). That's not what you want to write, but that's what you are writing.

If you only want to write binary data, you shouldn't be using a Writer at all. Just use OutputStream - wrap it in DataOutputStream if you want, but don't use a Writer. The Writer classes are for text.

people

See more on this question at Stackoverflow