Re: [pure-lang-users] C float
Status: Beta
Brought to you by:
agraef
From: Albert G. <Dr....@t-...> - 2008-08-13 21:33:46
|
Eddie Rucker wrote: > Then from Pure: > > using "lib:/t2.so"; > > extern int foo(int); > > let a = 2147483646; > > foo (a div -1); > -2147483645 Nothing wrong there, a div -1 == -2147483646 in signed arithmetic, so foo (a div -1) == -2147483646+1 == -2147483645. > Now, the following C program gives different results: > [...] > unsigned int a = 2147483646; > > printf("%d\n", foo(a/-1)); Note that the 'a/-1' here does *unsigned* arithmetic (because you declared a as such), which means a/-1 == a/0xffffffffU == 0 != -2147483646 == (signed)a/-1. If you declare a as a signed int in your C program, you'll get exactly the same result as with Pure. Under all circumstances, the C interface should behave as if the C int type is "cast" to the Pure int type and vice versa (using truncation and sign extension as necessary), if that's not the case then please report it and I will fix it. I think that this is the most reasonable way to implement the marshalling of C ints considering the limited repertoire of integer types available in Pure. Of course, this means that a C unsigned int return value will become negative in Pure if it's big enough. But that can be easily undone with the following little Pure function which takes a Pure int x and returns a bigint equal to (unsigned)x in C: uint x::int = if x>=0 then bigint x else x+0x100000000L; This carries over to unsigned 8, 16 and 64 bit ints accordingly: ubyte x::int = if x>=0 then x else x+0x100; ushort x::int = if x>=0 then x else x+0x10000; ulong x::bigint = if x>=0 then x else x+0x10000000000000000L; These always use the smallest Pure int type capable of holding the result: int for ubyte and ushort, bigint for uint and ulong. (Note that in the case of 64 bit values the C interface returns a bigint, that's why ulong takes a bigint parameter.) Maybe I should add those definitions to primitives.pure? HTH, Albert -- Dr. Albert Gr"af Dept. of Music-Informatics, University of Mainz, Germany Email: Dr....@t-..., ag...@mu... WWW: http://www.musikinformatik.uni-mainz.de/ag |