| Author |
Add length in front of a string
|
Thomas Poffet
Greenhorn
Joined: Mar 28, 2008
Posts: 9
|
|
I need to add a length to a string which I am sending via socket connection to an external system. The format is: first 4 bytes having the length followed by data.
Should look like: 0x00, 0x00, 0x00, 0xA1, < data stream with the length of 161 characters (0xA1) >.
Doing things like: int i= 161; StringBuffer sb = new StingBuffer(); sb.insert((char)i) works up to 127. Char should be unsigned, but not supported with Java.
Any idea? Thanks.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19232
|
|
Use a DataOutputStream around the socket's OutputStream, and a DataInputStream around the receiving socket's InputStream. You can then use writeInt / readInt to write / read the int. This way you're letting these two classes do the conversion for you.
In fact, you can use writeUTF / readUTF to send entire Strings through the socket.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
 |
|
|
subject: Add length in front of a string
|
|
|