Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Read integers from a char array buffer

 
Siamak Saarmann
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I have a char array buffer of data (contains different data types) sent by a server (developed in C++) over socket connection.

Now I want to read an integer (4 bytes) from a specific offset in the char array.

How should I do this?

Regards,
Mac
 
Carey Evans
Ranch Hand
Posts: 225
Debian Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your answer is nearly in your question. If you )]wrap a byte array from the server in a ByteBuffer and set the correct byte order, you can get integers, characters and other types from arbitrary offsets in the buffer.
 
Siamak Saarmann
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

Thank you very much. But I have char array.

In order to convert the char[] to byte[], I guess I need to first convert char[] to string and then use getByte method of the string.

However the char[] contains binary data (which might change due to conversion to String and from it). Am I right?

Thank you again.



PS: By the way I have used char[] because I use BufferedReader and InputStreamReader for socket programming.
 
Carey Evans
Ranch Hand
Posts: 225
Debian Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Unless the InputStreamReader is using the ISO-8859-1 encoding, there may not be enough information left in the character array to get the binary data back out. For example, the integer 1000, in little endian order, is the bytes [-24, 3, 0, 0]. If you convert that to characters encoded as UTF-8 via an InputStreamReader, then back via a String, you get [-17, -65, -67, 3, 0, 0].

Without knowing any more about your protocol, I think you will need to switch to reading to a byte array (or ByteBuffer) to read the 4-byte integers correctly.
 
Norm Radder
Ranch Hand
Posts: 728
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is the server sending the data in Unicode characters? Or is your read method converting the original input to characters? InputStreamReader is a bridge from byte streams to character streams.
What is the format for the data coming from the server? Maybe you need to tailor your read routine to read the data in the same format it is sent in.
[ July 30, 2008: Message edited by: Norm Radder ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic