ARM Technical Support Knowledge Articles

DIVISION DOESN'T WORK

Applies to: C51 C Compiler

Answer

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.

Article last edited on: 2004-05-10 21:24:26

Rate this article

[Bad]
|
|
[Good]
Disagree? Move your mouse over the bar and click

Did you find this article helpful? Yes No

How can we improve this article?

Link to this article
Copyright © 2011 ARM Limited. All rights reserved. External (Open), Non-Confidential