Xref: utzoo comp.std.unix:490 comp.lang.c:24997 comp.std.c:2342 Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!cs.utexas.edu!fletcher From: stealth.acf.nyu.edu!brnstnd@longway.tic.com (Dan Bernstein) Newsgroups: comp.std.unix,comp.lang.c,comp.std.c Subject: Re: How to convert a char into an int from 0 through 255? Message-ID: <7544@cs.utexas.edu> Date: 10 Jan 90 01:27:10 GMT Sender: fletcher@cs.utexas.edu Reply-To: Dan Bernstein Followup-To: comp.std.unix Organization: IR Lines: 33 Approved: fletcher@cs.utexas.edu (Guest Moderator, Fletcher Mattox) Apparently (int) (unsigned char) ch is guaranteed to be nonnegative and at most UCHAR_MAX, as long as sizeof(int) > sizeof(char). (If sizeof(int) == sizeof(char), there's obviously no way to fit all the characters into just the positive integers.) This answer is reasonably portable, though pre-ANSI machines must define UCHAR_MAX explicitly. I really did mean this as a UNIX C question, not just a C question; but POSIX doesn't seem to say anything about casts. Some other answers: (int) (unsigned int) ch will convert negative characters into negative integers, so it's wrong if char runs from, say, -128 to 127. ((int) ch) & 0xff works and answers my original question, but it won't handle machines with more than 256 characters. There's no compile-time way to find the right bit pattern---UCHAR_MAX + 1 may not be a power of two. ((int) ch) + UCHAR_MAX + 1) % (UCHAR_MAX + 1) produces the same result as (int) (unsigned char) ch (that is, if sizeof(int) > sizeof(char); otherwise it fails miserably) but is slow on most machines. This is a wonderful opportunity for me to make fun of the mathematical naivete that allows a negative value for x % y in some cases. *(unsigned char *)&ch seems an awfully complicated way to cast ch to an unsigned char. (Technically, it doesn't answer my question, because the result isn't an int.) Yes, Bill, I do have ch in a register, so forget it. ---Dan Volume-Number: Volume 18, Number 16