Min (minimum) maths problem

styrophil

Member
Found the answers to most of my problems here but this one has got me stumped.

I'm incrementing and decrementing a byte using buttons on a 12 button keypad. The values in the byte need to be limited to a range of 0-99. If I use the following...

Code:
select key_value
	case = 1
	let b0 = b0 + 1 max 99
	goto Store_and_set
	case = 7
	let b0 = b0 - 1 min 0
	goto Store_and_set
endselect
then the increment is fine and dandy but the decrement wraps round from 0 to 255 rather than sticking at 0

If I use...

Code:
select key_value
	case = 1
	let b0 = b0 + 1 max 99
	goto Store_and_set
	case = 7
	if b0 > 0 then dec b0 endif
	goto Store_and_set
endselect
everything works perfectly (at the cost of a couple of extra bytes of space)

So is that the way the min function is meant to work? Does it not work for at zero or have I got my syntax mixed up somewhere?

Using a 28X2 and a AXE033 LCD for display
 

Technical

Technical Support
Staff member
2 - 1 = 1 ok
1 - 1 = 0 ok
0 - 1 = 255, which is greater than 0 and so still okay!

So basically min won't work as you expected on 0.
 

SilentScreamer

Senior Member
Depending upon what you code does you might be able to save space by using 1-100 rather than 0-99. You can then use min but if you have to convert it back to 0-99 (to send to a LCD for example) it won't be beneficial any more.
 

styrophil

Member
Many thanks for the quick replies.

Technical - yes I wondered if it was something like that but wasn't sure.

SS - Thanks for the suggestion. Yes I would have to convert it back. The solution I used above only cost a few extra bytes so I can live with it at this point.

Many thanks again.
 

hippy

Ex-Staff (retired)
Instead of "let b0 = b0 - 1 min 0" which doesn't work ( as explained), you can jiggle that maths about and make sure b0 is always a minimum of 1 before subtracting 1 from it, so it will never become ' less than zero' ...

let b0 = b0 min 1 - 1

If b0 were zero, it gets increased to 1 first, then has 1 subtracted from it.
 

tiscando

Senior Member
Yep, that's what I do.

If subtracting a variable by a variable, then I use this to prevent underflow:
b0=b0 min b1 - b1
or
b0=b0 min 8 - 8

If adding, then I could use this to definitely prevent overflow:
b2=255-b1
b0=b0 max b2 +b1
 
Last edited:

BCJKiwi

Senior Member
Other options / sizes - sometimes the more elegant construct uses more memeory than the more basic construct.
Code:
symbol Key_Value = b10
 
#rem
select key_value
 case = 1
 let b0 = b0 + 1 max 99
 goto Store_and_set
 case = 7
 let b0 = b0 min 1 - 1
 goto Store_and_set
endselect
;31 bytes
#endrem
 
#rem
select key_value
 case = 1
 let b0 = b0 + 1 max 99
 goto Store_and_set
 case = 7
 if b0 > 0 then dec b0 endif
 goto Store_and_set
endselect
;34 Bytes
#endrem
 
#rem
If Key_Value = 1 then
  let b0 = b0 + 1 max 99
ElseIf Key_Value = 7 and b0 > 0 then
  dec b0
EndIf
Goto Store_and_Set
;29 bytes
#Endrem
 
Store_and_Set:
 
Last edited:
Top