Hallo,
Ich mochte ein integer shift right function fuer Integer schreiben mit richtigen abrundung. Die Code ist kein problem. Als ich aber innerhalb die Funktion auswerte:
test =-40 <=32675
dan ergibt sich test = 0 (im simulator)
wenn ich dass gleiche im Hauptprogram mache ergibt sich test = 1.
Wass passiert hier? Ich kann die Fehler nich finden.Code:'Program Shiftintr 'Contains demo of function Shiftintr_PR 'This function shifts integers right and works correctly with integers. It does arithmetic shifting 'The shift in Bascom is a logical shift, so the sign bit gets lost. 'To get the sign bit back, for negative numbers the result from the shift is subtrakted from 32768 (=max of int + 1) 'Based upon shiftintr, that did do the same with rounding towards negative infinity. 'This version of shiftint does proper rounding instead of rouding all numbers towards negative infinity 'var = variable to be shifted, N = number of shifts $regfile "m168def.dat" 'Frame and stack settings $framesize = 64 $swstack = 64 $hwstack = 64 'System frequency (20Mhz) $crystal = 20000000 Declare Function Shiftintr_pr(var As Integer , Byval N As Byte) As Integer Dim A As Integer Dim B As Integer Dim C As Integer Dim D As Integer Dim Test As Integer Dim Test1 As Integer A = -40 B = -39 C = -38 D = -37 Test = A <= 32765 D = D / 4 A = Shiftintr_pr(a , 2) B = Shiftintr_pr(b , 2) C = Shiftintr_pr(c , 2) End 'end program 'This function shifts integers right and works correctly with integers. It does arithmetic shifting 'The shift in Bascom is a logical shift, so the sign bit gets lost. 'To get the sign bit back, for negative numbers the result from the shift is subtracted from 32768 (=max of int + 1) 'var = variable to be shifted, N = number of shifts 'Note: this logical shift does rounding toward negative infinity (i.e. downwards) on all numbers Function Shiftintr_pr(var As Integer , Byval N As Byte ) As Integer Local P As Integer 'local variable for calculations (for demo purposes it is global here) Local I As Integer 'local counting variable (for demo purposes it is global here) Local Nloop As Byte 'Local variable to determine the rounding constant Local Maxn As Integer 'This is the maximum number that allows adding half the divisor without causing overflow P = Var P = 1 'Initialse P Nloop = N - 1 'Initialise Nloop based on the shift For I = 1 To Nloop P = 2 * P 'calculate 2^N-1 (this is half of the divisor) Next Maxn = 32767 - P 'calculate Maxn 'Maxn = 30000 Test1 = -40 <= 32765 Test = Var <= Maxn If Var <= Maxn Then 'In case overflow will not occur P = P + Var 'Add half the divisor Else P = Var End If For I = 1 To N 'This is the actual arithmetic shift Shift , P , Right , 1 'Shift one step If Var < 0 Then P = P - 32768 'correct sign for negative numbers only End If Next Shiftintr_pr = P 'load function variable with result of calculation End Function
Danke fuer jede hilfe.
Merijn







Zitieren

Lesezeichen