Borrar filtros
Borrar filtros

Convert ASCII symbols to numbers

8 visualizaciones (últimos 30 días)
Alessandro Russo
Alessandro Russo el 8 de Abr. de 2016
Comentada: Walter Roberson el 8 de Abr. de 2016
Hi all, i am receiving via COM port, some values from a bluetooth module, sent by my phone. These value, read with "fread", are in ASCII, so i must convert them in Matlab to get the decimal values. The problem is that if i send an integer, as 5, with "str2num" i get the correct number, but if i send a double like 5.3, i get a NaN; now if i use str2double, 5.3 is read correctly, but with this function an integer number is not read and i get a NaN. So in the end it seems that i can use only str2num for integers, and only str2double for floats. But if i send both integer and float numbers, how can i do to get in Matlab the correct values? Thanks in advance.

Respuestas (1)

Walter Roberson
Walter Roberson el 8 de Abr. de 2016
>> str2double('5'),str2double('5.'),str2double('5.3')
ans =
5
ans =
5
ans =
5.3
so it is incorrect that str2double does not work on integers.
Now, what might be going on is that when you think that you are sending integers, what you are sending is the binary values corresponding to the integers, so for example 5 being transmitted as a byte whose binary value is 5, whereas when you think you are sending floating point, what you are sending is the character representation, so for example 5 being transmitted as floating point might be sent as '5', binary 53.
Mixing text representation and binary representation usually leads to problems, and is most easily handled by using a strictly fixed length for the text representation -- which requires knowing the "never to exceed" values for your data so you can plan the field widths. Remember to plan for negative signs if needed.
  2 comentarios
Alessandro Russo
Alessandro Russo el 8 de Abr. de 2016
Ok, so i didn't explain correctly; i send for sure binary values, but (i don't know how), when they arrive to Matlab they are the for example 53 in the first position of the output vector of fread, which is the ASCII 5 (together with an endline "10" in the following vector position actually, then the other number in the following position, then the endline an so on). The question is, known that this is what arrives to Matlab, how should i convert it to read the decimal?
Walter Roberson
Walter Roberson el 8 de Abr. de 2016
fscanf(s, '%f', 1)
If you received a bunch of uint8, such as from using fread(s), then
str2double(char(TheBuffer))
or
sscanf(char(TheBuffer), '%f')
The first of those is probably more efficient.

Iniciar sesión para comentar.

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by