View Single Post
  #2   Spotlight this post!  
Unread 21-02-2004, 19:23
gnormhurst's Avatar
gnormhurst gnormhurst is offline
Norm Hurst
AKA: gnorm
#0381 (The Tornadoes)
Team Role: Programmer
 
Join Date: Jan 2004
Location: Trenton, NJ
Posts: 138
gnormhurst will become famous soon enoughgnormhurst will become famous soon enough
Re: Interger Representation - Huh?!

Quote:
Originally Posted by Jeff McCune
Not sure if I missed something in my CIS classes, but can someone offer some insight into this behavior?
Code:
int foo;
foo = 127 + 127;
printf ("%16b | %d \r\n", foo, foo);
// prints: "1111 1111 1111 1110 | -2"
Is this a bug in the printf code, or is the compiler and microchip actually representing this using ones for the first 15 significant digits and a zero at the least significant position?
The compiler has a documented non-standard behavior that may relate to this. See below, from the C18 compiler reference manual (available on the Microchip site).

2.7 ISO DIVERGENCES

2.7.1 Integer Promotions
ISO mandates that all arithmetic be performed at int precision or greater. By default, MPLAB C18 will perform arithmetic at the size of the largest operand, even if both operands are smaller than an int. The ISO mandated behavior can be instated via the -Oi command-line option.

For example:

Code:
unsigned char a, b; 
unsigned i;
a = b = 0x80;
i = a + b; /* ISO requires that i == 0x100, but in C18 i == 0 */
Note that this divergence also applies to constant literals. The chosen type for constant literals is the first one from the appropriate group that can represent the value of the constant without overflow.

For example:

Code:
#define A 0x10 /* A will be considered a char unless -Oi specified */
#define B 0x10 /* B will be considered a char unless -Oi specified */
#define C (A) * (B)
unsigned i;
i = C; /* ISO requires that i == 0x100, but in C18 i == 0 */

=====

It is confusing. I think you could cast the literal as an (int):

Code:
foo = (int)127 + (int)127;
Or maybe this?

Code:
foo = 127L + 127L;
I haven't tried these.

Last edited by Joe Johnson : 21-02-2004 at 21:58.