home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 January / usenetsourcesnewsgroupsinfomagicjanuary1994.iso / sources / std_unix / volume.18 / text0015.txt < prev    next >
Encoding:
Text File  |  1990-03-18  |  1.4 KB  |  35 lines

  1. Apparently (int) (unsigned char) ch is guaranteed to be nonnegative
  2. and at most UCHAR_MAX, as long as sizeof(int) > sizeof(char). (If
  3. sizeof(int) == sizeof(char), there's obviously no way to fit all the
  4. characters into just the positive integers.) This answer is reasonably
  5. portable, though pre-ANSI machines must define UCHAR_MAX explicitly.
  6.  
  7. I really did mean this as a UNIX C question, not just a C question; but
  8. POSIX doesn't seem to say anything about casts.
  9.  
  10. Some other answers:
  11.  
  12. (int) (unsigned int) ch will convert negative characters into negative
  13. integers, so it's wrong if char runs from, say, -128 to 127.
  14.  
  15. ((int) ch) & 0xff works and answers my original question, but it won't
  16. handle machines with more than 256 characters. There's no compile-time
  17. way to find the right bit pattern---UCHAR_MAX + 1 may not be a power of
  18. two.
  19.  
  20. ((int) ch) + UCHAR_MAX + 1) % (UCHAR_MAX + 1) produces the same result
  21. as (int) (unsigned char) ch (that is, if sizeof(int) > sizeof(char);
  22. otherwise it fails miserably) but is slow on most machines. This is a
  23. wonderful opportunity for me to make fun of the mathematical naivete
  24. that allows a negative value for x % y in some cases.
  25.  
  26. *(unsigned char *)&ch seems an awfully complicated way to cast ch to an
  27. unsigned char. (Technically, it doesn't answer my question, because the
  28. result isn't an int.) Yes, Bill, I do have ch in a register, so forget it.
  29.  
  30. ---Dan
  31.  
  32.  
  33. Volume-Number: Volume 18, Number 16
  34.  
  35.