Obtaining double by socket

4 respostas
J

Hello,

I’m developing a project that consists on an embedded system on a 8 bit microcontroller comunicating with a Java Application on a PC via sockets, and I have a question regarding Java data types.

What I want to do is: transmit an array of float values via socket, and my question is: Is there a way to store the data I receive via socket just as byte value and later on cast the values to the type I want?

I tried to learn how to do that but the socket’s InputStream is only prepared to receive chars or Strings, can I receive my data as a String, get blocks of 4 bytes(the size of the float on the uC) and put it on a float or double variable in Java? Anyone knows how to do that?

Thanks
Joao

4 Respostas

E

Let’s say that the controller generated the following floating-point number: 3.1416
Does the controller implement the IEEE-754 format ? http://en.wikipedia.org/wiki/IEEE_floating_point

If it does, are the bytes sent by the controller in big-endian or little-endian format?

The java.io.DataInputStream has a method (readFloat) that can read 4-byte floats if they follow the IEEE-754 format and in big-endian format.

J

Imagino que o float siga o padrão sim, desculpem por postar em inglês, me confundi entre os fóruns, esse aqui é brasileiro.

Eu estava usando um buffered reader por isso não conseguia ver os métodos que recebem outros tipos de dados, obrigado.

E

Tio, se você trafega dados binários entre o seu equipamento e o seu programa, não use nenhuma das classes que terminam por “Reader” ou “Writer” porque elas trabalham com caracteres, não com bytes, e isso dá muitos problemas.
O menor deles é que um byte pode acabar representando 2 caracteres, ou 2 bytes podem representar um caracter, ou então um byte acaba se transformando no caracter “?”.
Além disso, muito provavelmente você não poderá usar diretamente os métodos writeUTF e readUTF porque eles supõem strings “contadas” - ou seja, cada string é convertida para UTF-8, e então 2 bytes são prefixados a esses bytes convertidos da string, contendo o número de bytes da string. Vou dar um exemplo.

J

Tio?

Criado 29 de abril de 2013
Ultima resposta 29 de abr. de 2013
Respostas 4
Participantes 2