On 14-01-28 04:00 AM, Richard wrote:
On
28/01/2014 02:24, mike sander wrote:
I have been working on tests for cast().
i have run into some
inconsistent behaviour with casting to char type. casting any
numeric
type to any other numeric type (and logical) seems well
behaved. In
cases where the input value is outside the range of the output
type, the
output is set to the min/max of the output type as would be
expected.
With cast to char, the behavior is different. Here are a couple
of
simple examples using direct type conversion:
Case 1: expect char 0 (got undefined). equivalent to cast (
int8(-128),
"char")
>> x=int8(-128)
x = -128
>> z=char(x)
warning: range error for conversion to character value
error: value on right hand side of assignment is undefined
Case 2: expect char 0 (got 0. this one works as expected).
Equivalent
to cast(single(-128),"char")
>> x=single(-128)
x = -128
>> z=char(x)
warning: range error for conversion to character value
z =
>> single(z) # use this to output a printable value
ans = 0
>>
Case 3: expect char 255 Equivalent to cast(single(1000),"char")
>> x=single(1000)
x = 1000
>> z=char(x)
warning: range error for conversion to character value
z =
>> single(z) # use this to output a printable value
ans = 0
For info, Matlab R2013a returns:
>> x=int8(-128)
x =
-128
>> z=char(x)
Warning: Out of range or non-integer values truncated during
conversion to character.
(Type "warning off MATLAB:nonIntegerTruncatedInConversionToChar"
to suppress this warning.)
z =
This looks like 0. Consistent with what i expected (but did not get
from Octave). Truncate negative to zero.
>> x=single(-128)
x =
-128
>> z=char(x)
Warning: Out of range or non-integer values truncated during
conversion to character.
(Type "warning off MATLAB:nonIntegerTruncatedInConversionToChar"
to suppress this warning.)
z =
>> single(z)
ans =
0
Consistent with what i did expect (and get from Octave). negative
is truncated to zero.
>>
x=single(1000)
x =
1000
>> z=char(x)
z =
?
>> single(z)
ans =
1000
>>
Interesting. No warning. No truncation. maybe char is larger than
8 bit? looking at matlab docs for char:
Description
S = char(X) converts array X of nonnegative integer codes
into a character array. Valid codes range from 0 to 65535, where
codes 0 through 127 correspond to 7-bit ASCII characters. The
characters that MATLAB® can process (other than 7-bit ASCII
characters) depend upon your current locale setting. To convert
characters into a numeric array, use the double function.
Internally Octave uses unsigned 8 bit values (as far as I can
tell) for char. At a minimum it should truncate larger values to
255. I will try to patch.
Richard
|