Float to short conversion error in c

cpic

I implemented dc motor speed control project but there is one problem which i am not able to figure out .The problem is that my pid output which is float when assigned to short data type gives unexpected answer.since PWM inbuilt function in mikroc allows only short type dutycycle there is a need of float to short conversion.
please help
i am using pic16F877A.

    example 
    float to short conversion:
    float pid_out;
    short duty=(short)pid_out;
    outputs:
    if my pid_out<=100
    then duty=pid_out;
    and if my pid_out>100
    duty=65535

for pid_out values less than or equal to hundred it gives same value for duty
whereas for pid_out values greater than 100 it gives duty value in the range of 65500.
please help unable to understand what is the mistake.
For reading the values i used virtual terminal and uart.

Best Answer

You should know that casting float to int or short, can result in undefined behavior, if the float has a value outside the range of the integer. So, if that is possible, you should think about how to handle the exception cases, if pid_out>255, or pid_out<0.

Otherwise the answer to your question is to use a "unsigned short" data type:

unsigned short duty=(unsigned short)pid_out;

This casts pid_out in the range 0..255, the same range as duty can hold.

See http://en.wikipedia.org/wiki/C_data_types for a list of C data types.