Not Converting ASCII to DECIMAL

42 ビュー (過去 30 日間)
Elliot Alderson
Elliot Alderson 2019 年 11 月 23 日
コメント済み: the cyclist 2019 年 11 月 24 日
I have converted decimal number to ASCII, however I cannot turn the same ASCII code back to it's decimal.
Here is the code:
%DECIMAL TO ASCII
a = 1;
%dec2bin(a); % decimal to binary conversion
b = double(num2str(a)); % decimal to ASCII conversion
%OP TO ASCII
%ASCII TO DECIMAL
c= str2double(b); %ISSUE
d=str2num(b); %ISSUE

回答 (2 件)

the cyclist
the cyclist 2019 年 11 月 23 日
c = b-'0'
  2 件のコメント
Elliot Alderson
Elliot Alderson 2019 年 11 月 24 日
This solves the issue that I'm having, but how is it working?
the cyclist
the cyclist 2019 年 11 月 24 日
I poked around for some specific documentation on this behavior, but didn't find it.
I believe what is happening is that MATLAB converts the character array, so the above is equivalent to
c = b - double('0')

サインインしてコメントする。


per isakson
per isakson 2019 年 11 月 23 日
編集済み: per isakson 2019 年 11 月 24 日
I guess the problem is in the meaning of "Converting ASCII to DECIMAL".
The character '1' is represented by the decimal ascci number 49.
The function double() converts from character to decimal ascci number
>> double('1')
ans =
49
and char() converts from decimal ascci number to character
>> char(49)
ans =
'1'
str2double() and num2str() are something else. Look them up in the documentation.
>> str2double('1')
ans =
1
>>
>> num2str( 1 )
ans =
'1'
>>
  2 件のコメント
Elliot Alderson
Elliot Alderson 2019 年 11 月 24 日
編集済み: per isakson 2019 年 11 月 24 日
I understand your first line of code, but the current issue that I have is that I take the decimal number from the user, but I am having trouble converting that number to ascii. For example:
n1=input('Enter n1: ');
a=double(n1);
would not give me the ascii of said number, the double would be the same, since I'd be putting interger values in there in the first place. Whereas If I write a like:
a=double('n1');
This would only convert the characters 'n' and '1' into ASCII, not the user input.
per isakson
per isakson 2019 年 11 月 24 日
編集済み: per isakson 2019 年 11 月 24 日
Run and answer with the keystrokes "1" and "Enter"
%%
n1=input('Enter n1: ');
class( n1 )
the output in the Command Window will be
Enter n1: 1
ans =
'double'
Thus, n1 returned by input() is already double. Matlab is smart enough to understand that the user wants a double :(
Run and answer with the keystrokes "1" and "Enter"
n1=input('Enter n1: ', 's' ); % notice the 's'
class( n1 )
the output in the Command Window is now
Enter n1: 1
ans =
'char'
The 's' forces input() to return characters and thus
a=double(n1)
returns decimal ascii numbers
a =
49

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by