drmortalwombat / oscar64

Optimizing Small memory C Compiler Assembler and Runtime for C64
GNU General Public License v3.0
260 stars 21 forks source link

Unsigned Int Issue #5

Closed josipk closed 1 year ago

josipk commented 1 year ago

Unsigned Int is behaving like Singed Int. (Linux build environment)

include

include

include <c64/types.h>

int main(void) {

unsigned int n = 32760;
int i;

for(i=0; i<10; i++) {
    n++;
    printf("%d\n",n);
}
return 0;

}

output: 32761 32762 32763 32764 32765 32766 32767 -32768 -32767 -32766

drmortalwombat commented 1 year ago

This is expected behaviour. The int type is 16 bit, and if you print it as signed with the %d you get the first bit interpreted as -32768. You might want to use the %u formatter in the printf to get an unsigned result.

josipk commented 1 year ago

OK, so incorrect printf format. Thank You.

josipk commented 1 year ago

One more question, does the sqrt function work correctly with unsigned int?

include

include

include <c64/types.h>

include

include

int main(void) {

unsigned int n = 32760;
int i;

for(i=0; i<10; i++) {
    n++;
    int l=(int) sqrt(n);
    printf("%u,%d\n",n,l);
}
return 0;

}

output:

32761,181 32762,181 32763,181 32764,181 32765,181 32766,181 32767,181 32768,0 32769,0 32770,0

drmortalwombat commented 1 year ago

It appears unsiged int to float does not work. But you can use Dijkstras integer square root instead: `// Integer square root based on Dijkstras algorithm

unsigned tsqrt(unsigned n) { unsigned p, q, r, h;

p = 0;
r = n;

assign q 0x4000

repeat

{
    h = p | q;
    p >>= 1;
    if (r >= h)
    {
        p |= q;
        r -= h;
    } 
}

assign q q >> 2

until q == 0

undef q

return p;

} `

drmortalwombat commented 1 year ago

There is also a version in <gfx/bitmaph.> // Fast unsigned integer square root unsigned bm_usqrt(unsigned n);

josipk commented 1 year ago

Thank You, btw. the compiler is awesome :)