File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Read integers from a char array buffer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Read integers from a char array buffer" Watch "Read integers from a char array buffer" New topic
Author

Read integers from a char array buffer

Siamak Saarmann
Ranch Hand

Joined: Aug 21, 2004
Posts: 78
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


PhD Artificial Intelligence, OCJP1.6
Carey Evans
Ranch Hand

Joined: May 27, 2008
Posts: 225

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

Joined: Aug 21, 2004
Posts: 78
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

Joined: May 27, 2008
Posts: 225

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

Joined: Aug 10, 2005
Posts: 690
    
    1
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 ]
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Read integers from a char array buffer