How to convert a char into an int from 0 through 255?
Dan Bernstein
stealth.acf.nyu.edu!brnstnd at longway.tic.com
Wed Jan 10 12:27:10 AEST 1990
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
More information about the Comp.std.c
mailing list