How to calculate division to char?

Go To Last Post
8 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Hi

Now, I do not really understand about casting, but this is not working. Could someone shine his/her light on this? Many thanks ofcourse!

unsigned char LFOendval;  //between 0-128
unsigned char LFOdepth;   //between 0-128

char LFOtemp= ((float)(LFOendval/128))*LFOdepth;
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

You need to convert your char operand to float *before* doing the arithmetic, ie:

char LFOtemp = ( (float)LFOendval / 128 ) * LFOdepth;

or even simpler:

char LFOtemp = LFOendval / 128. * LFOdepth;

Note the decimal point after 128.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

So my initial solution was almost right :-)
That's nice to know! Good for my confidence ;-)

What does the point mean? Does it make the outcome a floating point number? Can I also do this:

char LFOtemp = (LFOendval / 128.) * LFOdepth;
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Yes that should work.

The official way to cast is by (float)(integer_value).

But if the integer_value is a constant and not a variable, the decimal point implies a float_constant. So the math will be done in floats and then transparently cast back to whatever you are assigning to.

The rules are clear but can be confusing. So it is always safer to use the conventional cast. Just make sure you put the cast in the right place.

David.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Since the result is stored back to a char, why use floating point at all? Why not just do:

char LFOtemp = LFOendval * LFOdepth / 128;
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

No idea, just tried it, and does work..
Sometimes i'm just looking at it the hard way...

The simplest solution is often the best.. Thanks for pointing that out.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

MusicMan wrote:

The simplest solution is often the best.. Thanks for pointing that out.

Not to mention that if you don't do floating point math at all, you don't reserve several hundred bytes of memory to floating point libraries and can do something else with it. Same goes with time.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Quote:

Since the result is stored back to a char, why use floating point at all? Why not just do:
Code:
char LFOtemp = LFOendval * LFOdepth / 128;

It may not be an issue under nearly all circumstances, but note that the multiply is often going to be 8x8=>16 bits. Maybe not a problem here, but then it will bite you when you do 16x16.

Lee

You can put lipstick on a pig, but it is still a pig.

I've never met a pig I didn't like, as long as you have some salt and pepper.