Hi Malcolm

On Monday 05 March 2012 Malcolm Lear wrote:
                              
It was I who required a way to do this. Thanks for this. Very well timed since 
I now need to print unsigned 32 bit integers and unfortunately none of the DEC$ 
functions can do this. Hopefully a few changes to this will provide a solution.

This was the comma$ function I wrote ...
 
750 DEFine FuNction comma$(num)
760 LOCal t, fra
770  IF num < 0 : RETurn "-" & comma$(ABS(num))
780  IF num < 1000 : RETurn num
790  IF num/1000 > 2^31-2 : RETurn num : REMark otherwise INT(num/1000) will 
fail
800  t = INT(num/1000)
810  fra = num - t*1000 : IF "e-" INSTR fra : fra = 0
820  RETurn comma$((t)) & "," & FILL$("0",(fra<100)+(fra<10)+(fra<1 AND fra>0)) 
& fra
830 END DEFine comma$

This function seems to be accurate for all integers within the 32 bit range.  
With higher values precision would be lost.
 
If I understand correctly, you want to print integers from 0 up to 2^32-1, when 
they are stored in the form -2^31 up to 2^31-1.  For a negative number, the 
absolute value is subtracted from 2^32.
 
Because we are outside of the 32 bit range of precision, subtraction is done 
using strings, with each digit subtracted separately, working from the right 
hand end to the left, using a carry flag, similar to the method used in primary 
school arithmetic.  This suggests something like the following ...
 
28430 DEFine FuNction unsigned_32bit$(num)
28440 LOCal x$(14), top$(13), bot$(13), ans$(13), carry, i, sum
28450   IF num < -2^31 OR num >= 2^31 : RETurn num
28460   IF ABS(num) - INT(ABS(num)) <> 0 : RETurn num
28470   x$ = comma$(num) : IF x$(1) <> "-" : RETurn x$
28480   top$ = comma$(2^32)
28490   bot$ = "0,000,000,000" : ans$ = bot$
28500   bot$(15-LEN(x$) TO 13) = x$(2 TO LEN(x$))
28510   carry = 0
28520   FOR i = 13,12,11, 9,8,7, 5,4,3, 1
28530     sum = top$(i) - ( bot$(i) + carry )
28540     IF sum < 0 : carry = 1 : ELSE carry = 0
28550     ans$(i) = sum + carry * 10
28560   END FOR i
28570   RETurn ans$
28580 END DEFine unsigned_32bit$

PRINT unsigned_32bit$(-1) gives 4,294,967,295
 
Michael Bulford
_______________________________________________
QL-Users Mailing List
http://www.q-v-d.demon.co.uk/smsqe.htm

Reply via email to