string 在 MATLAB 中从 ASCII 代码转换为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5192887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:00:50  来源:igfitidea点击:

Convert from ASCII code to string in MATLAB

stringmatlabascii

提问by Bill Cheatham

If I have a string in matlab, I can convert it to a vector of ASCII codes using double:

如果我在 matlab 中有一个字符串,我可以使用以下方法将其转换为 ASCII 代码向量double

>> my_string = 'asd';
>> double(my_string)

ans =

    97   115   100

How can I go back the other way? i.e., if I have an ASCII code in a MATLAB vector, how can I create the corresponding string?

我怎样才能从另一条路回去?即,如果我在 MATLAB 向量中有一个 ASCII 代码,我该如何创建相应的字符串?

e.g

例如

ascii_codes = [97 115 100];

should be converted to...

应该转换成...

my_string = 'asd'

回答by Marcus Fr?din

How about char(documentation)? Eg char(ascii_codes)?

如何char文档)?例如char(ascii_codes)

回答by Tommaso Belluzzo

A great alternative to the charfunction, in my opinion, is the native2unicodefunction. It handles many different encoding schemes, allowing you to explicitly specifying the one to be used through its second input argument:

在我看来,char函数的一个很好的替代方案是native2unicode函数。它处理许多不同的编码方案,允许您通过其第二个输入参数明确指定要使用的编码方案:

unicodestr = native2unicode(bytes, encoding) converts bytes to a Unicode representation with the assumption that bytes is in the character encoding scheme specified by encoding. The input argument encoding must have no characters ('') or it must be a name or alias for an encoding scheme. Some examples are 'UTF-8', 'latin1', 'US-ASCII', and 'Shift_JIS'. If encoding is unspecified or has no characters (''), the default encoding scheme is used. encoding can be a character vector or a string scalar.

unicodestr = native2unicode(bytes, encoding) 假设字节在由 encoding 指定的字符编码方案中,将字节转换为 Unicode 表示。输入参数 encoding 不得包含字符 (''),或者它必须是编码方案的名称或别名。一些示例是“UTF-8”、“latin1”、“US-ASCII”和“Shift_JIS”。如果未指定编码或没有字符 (''),则使用默认编码方案。encoding 可以是字符向量或字符串标量。

Usage example:

用法示例:

>> ascii_codes = [97 115 100];
>> my_string = native2unicode(ascii_codes,'ASCII')

my_string =

    'asd'