delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2003/07/27/20:30:03

From: Martin Ambuhl <mambuhl AT earthlink DOT net>
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.4) Gecko/20030624 Netscape/7.1 (ax)
X-Accept-Language: en-us, en, de, fr, ru, el, zh
MIME-Version: 1.0
Newsgroups: comp.os.msdos.djgpp
Subject: Re: integer overflow
References: <3F246120 DOT 63C3753C AT worldnet DOT att DOT net>
In-Reply-To: <3F246120.63C3753C@worldnet.att.net>
Lines: 26
Message-ID: <Z6_Ua.375$%S6.105@newsread1.news.atl.earthlink.net>
Date: Mon, 28 Jul 2003 00:28:41 GMT
NNTP-Posting-Host: 65.148.4.157
X-Complaints-To: abuse AT earthlink DOT net
X-Trace: newsread1.news.atl.earthlink.net 1059352121 65.148.4.157 (Sun, 27 Jul 2003 17:28:41 PDT)
NNTP-Posting-Date: Sun, 27 Jul 2003 17:28:41 PDT
Organization: EarthLink Inc. -- http://www.EarthLink.net
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

Paul Cousoulis wrote:
> Why does this code result in an integer overflow?
> 
> unsigned long res;
> 
> res = (1<<31)-1;

Because (1 << 31) is a signed expression. Never use signed integers for 
bit twiddling. Here's an example without such overflow.


#include <stdio.h>

int main(void)
{
     unsigned long res;
     res = 1LU << 31;
     printf("1LU << 31     : %lu\n", res);
     res = (1LU << 31)-1;
     printf("(1LU << 31)-1 : %lu\n", res);
     return 0;
}

1LU << 31     : 2147483648
(1LU << 31)-1 : 2147483647

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019