This week's book giveaway is in the General Computing forum.
We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line!
See this thread for details.
The moose likes Sockets and Internet Protocols and the fly likes Add length in front of a string Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Sockets and Internet Protocols
Reply Bookmark "Add length in front of a string" Watch "Add length in front of a string" New topic
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
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Add length in front of a string
 
Similar Threads
How to write to a file in exact position?
Internationalization - Japanese text
Converting Char array to String
javax.crypto with sun AND ibm...
Using single quotes in a SQL statement