Page 1 of 1

bit of maths help please

Posted: Thu Dec 29, 2011 10:15 am
by Steve001
Morning all , hope everyone had a good xmas :mrgreen:

I am stuck with this one, i have a project which reads all of the inputs for example "PORT C" and returned a value which can be 0 - 255 i want to be able to convert this into 1,2,3,4,5,6,7,8 so if i have a value of 20 i want to get an answer of 5 and 3 .
It has been a long time since i have done 2's Compliment stuff and i have forgot now :(

Steve

Re: bit of maths help please

Posted: Thu Dec 29, 2011 11:58 am
by Steve
There are more efficient ways, but you could do this in a "long" (but perhaps more intuitive) way. For example, something similar to the following...

Code: Select all

pin = 8
mask = 128

loop 8 times
  if (portc_val >= mask)
    //val found
    output pin
   
    portc_val = portc_val - mask
  endif

  pin = pin - 1
  mask = mask / 2
end loop
I'm not sure how you would want to output the result (especially as the result can be anything from zero to 8 different numbers), so I'll leave that part to you.

Re: bit of maths help please

Posted: Thu Dec 29, 2011 2:47 pm
by Steve001
Thanks for that steve, will have a go with that later

Re: bit of maths help please

Posted: Tue Jan 03, 2012 9:19 pm
by Steve001
trying to understand on how the example works

pin = 8
mask = 128

loop 8 times
if (portc_val >= mask)
//val found
output pin

portc_val = portc_val - mask
endif

pin = pin - 1
mask = mask / 2
end loop

Dont understand this . .

mask = 128

Should this be 255 ? if not why is it 128 ? or am i missing something :?

Re: bit of maths help please

Posted: Tue Jan 03, 2012 9:39 pm
by Steve001
It's ok think i have sussed it . . .

steve