• Post Reply Bookmark Topic Watch Topic
  • New Topic

Add length in front of a string  RSS feed

 
Thomas Poffet
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 21092
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!