フィルターのクリア

How do I do char2num (assume Ascii)?

31 ビュー (過去 30 日間)
Gavin
Gavin 2024 年 9 月 24 日 17:29
コメント済み: Stephen23 2024 年 9 月 24 日 17:53
num2 char is easy enough num = char(122) returns 'z' ; but how can I get back to the ascii value from a char?
Do I really have to do all this:
val = unicode2native(ch(1:1),'US-ASCII');
I suppose I can make
function val = char2num(ch) % return a single ascii value
if ischar(ch) || isstring(ch)
val = unicode2native(ch(1:1),'US-ASCII');
val = val(1:1); % because if it's a string ch(1:1) is the first string not the char
else % it's already a number?
ch = mod(ch,256); % Too big? take LSB
% oddly ML mod() allows fractions so ...
val = uint8(ch); % round if needed
end
But surely there is a built in function that I just can't find

採用された回答

Stephen23
Stephen23 2024 年 9 月 24 日 17:32
編集済み: Stephen23 2024 年 9 月 24 日 17:39
txt = char(120:122)
txt = 'xyz'
num = double(txt)
num = 1×3
120 121 122
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
If you have a container array (e.g. cell array or string array) then of course you will need to use a loop or CELLFUN/ARRAYFUN or something of that nature. For a scalar string array you could simply access its content using curly braces:
str = "xyz";
vec = double(str{1})
vec = 1×3
120 121 122
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
  3 件のコメント
Stephen23
Stephen23 2024 年 9 月 24 日 17:48
txt = char(120:122)
txt = 'xyz'
num = uint8(txt)
num = 1×3
120 121 122
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
You can add CHAR if you want it to work with both character arrays and scalar strings:
num = uint8(char(txt))
num = 1×3
120 121 122
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
Stephen23
Stephen23 2024 年 9 月 24 日 17:53
str = "xyz";
num = uint8(str{1}(1))
num = uint8 120

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

その他の回答 (0 件)

カテゴリ

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

タグ

製品


リリース

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by