Unicode 和 ASCII 值
MATLAB® 使用 UTF-16 编码将所有字符存储为 Unicode® 字符,其中每个字符都由数值代码表示。(Unicode 纳入了 ASCII 字符集作为其前 128 个符号,因此 ASCII 字符在 Unicode 和 ASCII 中具有相同的数值代码。)字符数组和字符串数组都使用此编码。您可以使用各种数值转换函数将字符转换为其数值代码。您可以使用 char
函数将数字转换为字符。
将字符转换为数值代码
您可以将字符转换为表示其 Unicode 代码值的整数。要转换单个字符或字符数组,请使用以下任一函数:
double
uint16
、uint32
或uint64
最佳做法是使用 double
函数。但是,如果您需要将数值存储为整数,请使用有至少 16 位的无符号整数,因为 MATLAB 使用 UTF-16 编码。
使用 double
函数将字符向量转换为 Unicode 代码值。
C = 'MATLAB'
C = 'MATLAB'
unicodeValues = double(C)
unicodeValues = 1×6
77 65 84 76 65 66
您无法将字符串数组中的字符直接转换为 Unicode 代码值。特别是,double
函数将字符串转换为它们所表示的数字,就像 str2double
函数一样。如果 double
无法将字符串转换为数字,则它返回 NaN
值。
str = "MATLAB";
double(str)
ans = NaN
要转换字符串中的字符,请先将字符串转换为字符向量,或使用花括号提取字符。然后使用 double
等函数转换字符。
C = char(str); unicodeValues = double(C)
unicodeValues = 1×6
77 65 84 76 65 66
将数值代码转换为字符
您可以使用 char
函数将 Unicode 值转换为字符。
D = [77 65 84 76 65 66]
D = 1×6
77 65 84 76 65 66
C = char(D)
C = 'MATLAB'
char
的典型用途是创建无法键入的字符,并将其追加到字符串中。例如,创建表示度符号的字符,并将其追加到字符串中。度符号的 Unicode 代码值是 176。
deg = char(176)
deg = '°'
myLabel = append("Current temperature is 21",deg,"C")
myLabel = "Current temperature is 21°C"
有关 Unicode 的详细信息,包括字符和代码值之间的映射,请参阅 Unicode。
另请参阅
char
| double
| single
| string
| int8
| int16
| int32
| int64
| uint8
| uint16
| uint32
| uint64