[Mono-list] [patch] System.BitConverter impl

Matt Kimball matt@kimball.net
Tue, 08 Jan 2002 10:58:05 -0800 (PST)


This is a multi-part message in MIME format...

------------=_1010516285-1335-0
Content-Type: text/plain; charset=iso-8859-1
Content-Disposition: inline
Content-Transfer-Encoding: binary

Paolo Molaro wrote
> Could you put the CSCompliant attribute and the unsafe keyword only
> where it's really needed? Looks good otherwise.

Okay, I've fixed this.  Attached is a new version.

As an added bonus, I also fixed the code to throw the correct exceptions when
the arguments are invalid.

> Did you find somewhere in the spec if it should always convert to
> little endian when converting, say, an int to a byte array?
> Or should it convert to the native endianess?

The documentation doesn't specify, but the intent seems to be to always convert
to native endianness.  I believe my code will do this, but it will always
*report* that it is running on a little endian machine, right now.  This should
probably be some sort of 'configure' derived magic, but I've just hardcoded the
boolean variable which reports it to "Yes, you are running on a little endian
machine."

-- 
Matt Kimball
matt@kimball.net



------------=_1010516285-1335-0
Content-Type: application/octet-stream; name="BitConverter.cs"
Content-Disposition: attachment; filename="BitConverter.cs"
Content-Transfer-Encoding: base64

Ly8KLy8gU3lzdGVtLkJpdENvbnZlcnRlcgovLwovLyBBdXRob3I6Ci8vICAg
TWF0dCBLaW1iYWxsIChtYXR0QGtpbWJhbGwubmV0KQovLwoKdXNpbmcgU3lz
dGVtOwoKbmFtZXNwYWNlIFN5c3RlbSB7CglwdWJsaWMgY2xhc3MgQml0Q29u
dmVydGVyIHsKCQlbTW9ub1RPRE9dCS8vICBOb3QgYWxsIHRoZSB3b3JsZCdz
IGFuIHg4NgoJCXB1YmxpYyBzdGF0aWMgcmVhZG9ubHkgYm9vbCBJc0xpdHRs
ZUVuZGlhbiA9IHRydWU7CgoJCXB1YmxpYyBzdGF0aWMgbG9uZyBEb3VibGVU
b0ludDY0Qml0cyhkb3VibGUgdmFsdWUpIHsKCQkJcmV0dXJuIFRvSW50NjQo
R2V0Qnl0ZXModmFsdWUpLCAwKTsKCQl9CgoJCXB1YmxpYyBzdGF0aWMgZG91
YmxlIEludDY0Qml0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