TIP: Click on subject to list as thread! ANSI
echo: c_echo
to: All
from: Bob Stout
date: 2004-04-27 07:55:50
subject: Re: [C] typecasting

From: Bob Stout 

On Sat, 24 Apr 2004, Jay B wrote:

> Hey, I got the following code:
>
> int main(void) {
>     int i = -33;
>
>     printf("%d\n", i);
>     printf("%d\n", (unsigned int)i);
>     return 0;
> }
>
> I get -33 for both, why? Since I'm typecasting the second as an unsigned
> int, shouldn't it get rid of the negative sign?

Try instead:

int main(void)
{
    int i = -33;

    printf("%d\n", i);
    printf("%u\n", (unsigned int)i);
    printf("%d\n", abs(i));
    return 0;
}

This should teach you everything you want to know:

1.  It will show you that casting to an unsigned int doesn't do what you
    think. Negative numbers are usually represented in twos-complement
    format, so the internal representation of -33 is 0xFFFFFFDF on a
    32-bit machine. Casting to an unsigned int merely tells the compiler
    that you want to interpret that number as unsigned rather than twos-
    complement, which results in the program displaying 4294967263 (I'm
    still assuming you're using 32-bit integers).

2.  If you do really ever want to print an unsigned int value, the
    specifier is "%u", not "%d".

3.  To change the sign, you should use the abs() function. You'll find the
    prototype in stdlib.h, which you should include (not strictly
    necessary, but simply good programming practice).

-------------------------------------------------------------
Consulting: http://www.MicroFirm.biz/ Web graphics development:
http://Image-Magicians.com/ Software archives:
http://snippets.snippets.org/
  c.snippets.org/   cpp.snippets.org/      java.snippets.org/
  d.snippets.org/   python.snippets.org/   perl.snippets.org/
  dos.snippets.org/ embedded.snippets.org/ apps.snippets.org/
Audio and loudspeaker design:
  http://LDSG.snippets.org/   http://www.diyspeakers.net/

--- BBBS/LiI v4.01 Flag-5
* Origin: Prism's_Point (1:261/38.1)
SEEN-BY: 633/267 270
@PATH: 261/38 123/500 106/2000 633/267

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.