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.
댓글 수: 0
답변 (1개)
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
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 Center 및 File Exchange에서 Data Type Conversion에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!