Convert ASCII symbols to numbers
8 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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.
0 comentarios
Respuestas (1)
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
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.
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!