Bug? long division result casted to int saturates to max in value instead of rolling over to the negative number

ema01

Member
Licensed User
Longtime User
It took me a while.
B4X:
dim a as long = 239939944437253
dim b as int = a / 65536
log(b)

I am primarly a C developer so what i would expect: perform the division as long and then cast the result to the appropriate size so - following c rules - it should become 3661192999 -> 0xDA395F27 -> -633774297, but i don't care about the sign because i'm checking individual bits.
however the result is 2147483647 -> 0x7FFFFFFF aka the maximum value for an integer.

Is this expected? As i said i am primarly a C developer and maybe the C mindset is fooling me in this case. If it's expected, where can i read up about this?
 

agraham

Expert
Licensed User
Longtime User
It's a Java narrrowing primitive conversion which is much smarter than that of C which basically does nothing.
Chapter 5. Conversions and Promotions (oracle.com)

The generated Java code looks like this
Java:
 //BA.debugLineNum = 40;BA.debugLine="Dim a As Long = 239939944437253";
_a = (long) (239939944437253L);
 //BA.debugLineNum = 41;BA.debugLine="Dim b As Int = a / 65536";
_b = (int) (_a/(double)65536);
 //BA.debugLineNum = 42;BA.debugLine="Log(b)";
Which results in a double (you'll have to ask Erel why the double cast is there) that is narrowed to an int on assignment. My boldening
Otherwise, one of the following two cases must be true: a. The value must be too small and the result is the smallest representable value of type int or b. The value must be too large and the result is the largest representable value of type int.
 

ema01

Member
Licensed User
Longtime User
Thanks for the explanation. I had a feeling it would be a java thing.
(The cast to double... i suspect it is to conform to BASIC? doesn't it use floating point for every computation then cast to the appropriate type?)
 

agraham

Expert
Licensed User
Longtime User
i suspect it is to conform to BASIC?
B4X doesn't try to conform to any other dialect of Basic.

doesn't it use floating point for every computation then cast to the appropriate type?
No, though it seems to occasionally do so. I don't know the rules for this. Its predecessor, Basic4ppc, did do all calculations as doubles but Erel changed this for Basic4Android which became B4A and then the more general B4X.
 
Top