Convert from ASCII code to string in MATLAB

匿名 (未验证) 提交于 2019-12-03 08:42:37

问题:

If I have a string in matlab, I can convert it to a vector of ASCII codes using 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?

e.g

ascii_codes = [97 115 100]; 

should be converted to...

my_string = 'asd' 

回答1:

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



回答2:

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

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.

Usage example:

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


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!