Technical Support

C51: DIVISION DOESN'T WORK

QUESTION

Help. I think I found a bug in the code generated for a divide in the C51 compiler. The following program performs a division, el_hi = (el_int / 256), that generates incorrect results. What's going on?

int  el_int;
char el_lo;
char el_hi;

void main()
{
        el_int = 0xfe53;

        while(1)
        {
                el_hi = (el_int / 256);
                el_lo = (el_int >> 8);
        }
}

ANSWER

The problem here does not lie in the compiler but in the code supplied. For example,

        el_int = 0xfe53;

//
// el_int is a signed integer.  0xFE53 is really -429.
//

                el_hi = (el_int / 256);

//
// el_hi is a signed character.  0xFE53 (-429) / 256 = -1 = 0xFFFF
// and 0xFFFF is yields 0xFF when converted to a character
//

The problem is caused by el_int being an integer and the division is performed on a SIGNED integer rather than an UNSIGNED integer. To solve this problem, change the type of el_int to unsigned int.

Last Reviewed: Monday, May 10, 2004


Did this article provide the answer you needed?
 
Yes
No
Not Sure