Reputation: 17408
Why does the expression:
test = cast(strtrim('3'), 'uint8')
produce 51?
This is also true for:
test = cast(strtrim('3'), 'int8')
Thanks.
Upvotes: 2
Views: 4833
Reputation: 74940
Because 51 is the ASCII code for the character '3'
.
If you want to transform the string to numeric 3, you should use
uint8(str2double('3'))
Note that str2double
will ignore trailing spaces, so that strtrim
isn't necessary.
EDIT
When a string is used in an numeric operation, Matlab automatically converts it to its ASCII value. For example
>> '1'+1
ans =
50
Upvotes: 4
Reputation: 1039
This is because '3' is seen as an ASCII character to matlab. By casting as a signed or unsigned integer (8 bits in this case) you are asking Matlab to convert an ASCII '3' to a decimal number. In this case the decimal number is 51. If you want to look at more conversions here is a basic document.
Upvotes: 1
Reputation: 272517
Because 51 is the ASCII value for the character '3'
.
Upvotes: 3