D
David Levine
Using v1.1. of the framework:
I was writing a wrapper around the java.util.zip.ZipOutputStream class so
that my app could access it using standard FileStream semantics and I ran
into a conversion problem. The signature for the write method is void
ZipOutputStream.Write(sbyte[] array,int off,int len) so I figured a simple
conversion from byte[] to sbyte[] would do the trick.
Now, my understanding of an sbyte is that it is a signed byte that can hold
values from -128 to 127. In hex 0x00 through 0x7f are positive values and
0x80 through 0xff are negative values.
When I wrote some test data the routine Convert.ToSbyte(byte) would throw an
overflow exception; this occurred for any value in the range of 0x80 - 0xff.
I then used Reflector to look at the BCL for Convert.ToSByte and the code
is...
[CLSCompliant(false)]
public static sbyte ToSByte(byte value)
{
if (value > 0x7f)
{
throw new
OverflowException(Environment.GetResourceString("Overflow_SByte"));
}
return (sbyte) value;
}
This surprised me - it specifically disallows all values that would result
in a negative value for the sbyte. So, is the BCL correct or should it
convert it to a negative value?
BTW: I wrote my own conversion method, tested it, and it all seems to work
correctly for all possible values of a byte.
if ( b > 0x7f )
sb = (sbyte)(0 - (0xff - b))
else
sb = (sbyte)b;
I was writing a wrapper around the java.util.zip.ZipOutputStream class so
that my app could access it using standard FileStream semantics and I ran
into a conversion problem. The signature for the write method is void
ZipOutputStream.Write(sbyte[] array,int off,int len) so I figured a simple
conversion from byte[] to sbyte[] would do the trick.
Now, my understanding of an sbyte is that it is a signed byte that can hold
values from -128 to 127. In hex 0x00 through 0x7f are positive values and
0x80 through 0xff are negative values.
When I wrote some test data the routine Convert.ToSbyte(byte) would throw an
overflow exception; this occurred for any value in the range of 0x80 - 0xff.
I then used Reflector to look at the BCL for Convert.ToSByte and the code
is...
[CLSCompliant(false)]
public static sbyte ToSByte(byte value)
{
if (value > 0x7f)
{
throw new
OverflowException(Environment.GetResourceString("Overflow_SByte"));
}
return (sbyte) value;
}
This surprised me - it specifically disallows all values that would result
in a negative value for the sbyte. So, is the BCL correct or should it
convert it to a negative value?
BTW: I wrote my own conversion method, tested it, and it all seems to work
correctly for all possible values of a byte.
if ( b > 0x7f )
sb = (sbyte)(0 - (0xff - b))
else
sb = (sbyte)b;