ARM Technical Support Knowledge Articles

ARITHMETIC PROBLEMS WITH CHAR TYPES

Applies to: C51 C Compiler

Answer


Information in this article applies to:


QUESTION

In the following Arithmatic Calculation:

data char k;
idata float adat;

k = 150;
adat = k;

adat is assigned the value -106.

Why did this happen and what is the solution for correct answer?

ANSWER

In the above code, you have assigned a value 150 to a char variable. By default, char types are stored in a byte and are signed. They can store values from -128 to 127.

The number 150 is not in this range and, therefore, cannot be represented by this type. Technically, 150 overflows the char type. The HEX value for 150 is 0x96 and that is what is stored in k. Since the MSb of k is set, the number is interpreted as a negative number (stored in two's complement). Negating 0x96 and adding 1 gives 0x6A which is -106.

The solution is to change the type of k to unsigned char (whose valid range is 0-255):

data unsigned char k;
idata float adat;

k = 150;
adat = k;

Article last edited on: 2004-09-03 14:14:48

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