🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c
Article #2178

Re: this unsigned business

#2178
From: T. William Wells
Date: Thu, 01 Oct 1992 08:14
36 lines
1918 bytes
In article <711@mtndew.Tustin.CA.US> friedl@mtndew.Tustin.CA.US (Stephen Friedl) writes:
:      Let's say that I've got an int whose legal range is 0 to 100,
: and I want to validate it (say) upon entry to a function.  Is this
: a portable way to do it?
:
:       foo(v)
:       int v;
:       {
:               if ( (unsigned int) v > 100)
:                       printf("value out of range!\n");

When casting an int to an unsigned int and the value is negative,
UINT_MAX+1 is added to get the result. Your test will work
provided that the value of all negative integers, cast to
unsigned, are > 100. Since that the two types are of the same
size and that a pure binary representation must be used,
excepting the signed bit, the largest negative integer can't be
over 1/2 the range of the unsigned integer, give or take a few.
This means that as long as your test is for a value less than 32K
minus, say, two, you are OK. (Someone else can figure out the
actual limits are, I don't care enough to bother.)

:      Note that I am not looking for the aesthetics of this -- it's
: a trick that will just confuse somebody -- just whether it is portable
: or not.  I know that it works on my machine, which doesn't prove
: much at all.

I've actually found a good use for this trick. On my system, there
is no isascii (because my headers are mostly ANSI) and this is a
real pain sometimes when porting code. This solves that problem:

#define isascii(x) ((unsigned int)(x) <= 255)

---
Bill                            { rutgers | decwrl | telesci }!twwells!bill
bill@twwells.com
Technical Details
Message-ID: <BvFo8x.Jq1@twwells.com>
Path: arc1-ca.pugleaf.net!sparky!uunet!decwrl!twwells!bill
References: <711@mtndew.Tustin.CA.US>

Show Full Headers
Complete Article Headers
Newsgroups: comp.std.c
Path: arc1-ca.pugleaf.net!sparky!uunet!decwrl!twwells!bill
From: bill@twwells.com (T. William Wells)
Subject: Re: this unsigned business
Date: Thu, 1 Oct 1992 08:14:55 GMT
Message-ID: <BvFo8x.Jq1@twwells.com>
References: <711@mtndew.Tustin.CA.US>
Organization: None, Mt. Laurel, NJ
Lines: 36