Convert ASCII symbols to numbers

8 次查看(过去 30 天)
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.

回答(1 个)

Walter Roberson
Walter Roberson 2016-4-8
>> 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 个评论
Alessandro Russo
Alessandro Russo 2016-4-8
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 2016-4-8
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by