Reputation: 121
I have declared a uint8 value as A = [4, 8, 16, 32];
and I casted to the value B = typecast(uint8(A), 'uint16')
, but the answer is 2052 8208
I would be very thankful if anyone could help me to understand the reason behind it.
Upvotes: 2
Views: 374
Reputation: 5822
MATLAB's typecast function converts the data type without changing the underlying data. In other words, it doesn't changes the underlying memory representation of the data structure, and simply treats it as a uint16 instead of uint8.
In your case, you want to preserve to original values of your data after casting. Therefore, you do want MATLAB to change the memory representation of the data structure. There are two ways to perform this type of casting:
-using cast function
B = cast(uint8(A), 'uint16');
-using a direct call to uint16 function:
B = uint16(A);
result:
B =
4 8 16 32
Upvotes: 2
Reputation: 564
You are probably expecting for Matlab to put your uint8
values just into uint16
variables. This is not what the typecast function is doing. It will preserve the number of bytes from the input to the output. So in your example, it merges the bit representation of 4 and 8 into a uint16
number and equivalently also 16 and 32.
So the binary representation of 4 is 00000100 and of 8 is 00001000 and merged together (to a 16bit number) they give 0000100000000100, which is 2052.
Upvotes: 3