typecast
Convert data types without changing underlying data
Syntax
y = typecast(x,键入)
Description
y = typecast(x,键入)
converts a numeric value inX
to the data type specified bytype
. InputX
must be a full, noncomplex, numeric scalar or vector. Thetype
输入是一个字符串设置为以下之一:'uint8'
,'int8'
,'uint16'
,'int16'
,'uint32'
,'int32'
,'uint64'
,'int64'
,'single'
, or'double'
.
typecast
与matlab不同®cast
function in that it does not alter the input data.typecast
always returns the same number of bytes in the outputY
as were in the inputX
. For example, casting the 16-bit integer 1000 touint8
withtypecast
returns the full 16 bits in two 8-bit segments (3 and 232) thus keeping its original value (3*256 + 232 = 1000). Thecast
另一方面,函数将输入值截断为255。
The output oftypecast
can be formatted differently depending on what system you use it on. Some computer systems store data starting with its most significant byte (an ordering called大端口), while others start with the least significant byte (calledlittle-endian).
不te
MATLAB issues an error ifX
contains fewer values than are needed to make an output value.
Examples
Example 1
此示例在相同大小的数据类型之间转换:
TypeCast(UINT8(255),'INT8')ANS = -1键盘(INT16(-1),'UINT16')ANS = 65535
Example 2
Set X to a 1-by-3 vector of 32-bit integers, then cast it to an 8-bit integer type:
X = uint32([1 255 256]) X = 1 255 256
Running this on a little-endian system produces the following results. Each 32-bit value is divided up into four 8-bit segments:
Y = typecast(X, 'uint8') Y = 1 0 0 0 255 0 0 0 0 1 0 0
The third element ofX
, 256, exceeds the 8 bits that it is being converted to inY
(9)因此溢出到Y
(10):
Y(9:12) ans = 0 1 0 0
不te thatlength(Y)
is equal to4.*length(X)
. Also note the difference between the output oftypecast
versus that ofcast
:
Z = cast(X, 'uint8') Z = 1 255 255
Example 3
此示例投用了较小的数据类型(uint8
)进入一个更大的人(uint16
). Displaying the numbers in hexadecimal format makes it easier to see just how the data is being rearranged:
十六进制格式X = uint8 ([44 55 66 77]) X = 2c 37 42 4d
The firsttypecast
is done on a big-endian system. The four 8-bit segments of the input data are combined to produce two 16-bit segments:
Y = typecast(X, 'uint16') Y = 2c37 424d
The second is done on a little-endian system. Note the difference in byte ordering:
Y = typecast(X, 'uint16') Y = 372c 4d42
You can format the little-endian output into big-endian (and vice versa) using theswapbytes
function:
y = swapbytes(typecast(x,'uint16'))y = 2c37 424d
Example 4
This example attempts to make a 32-bit value from a vector of three 8-bit values. MATLAB issues an error because there are an insufficient number of bytes in the input:
format hex typecast(uint8([120 86 52]), 'uint32') Error using typecast Too few input values to make output type.
Repeat the example, but with a vector of four 8-bit values, and it returns the expected answer:
TypeCast(UINT8([120 86 52 18]),'UINT32')ANS = 12345678