Peter said:
Eric said:
bd said:
Eric Sosman wrote:
[...]
Maybe there's a way to calculate (UINT_MAX + 1)/(UCHAR_MAX + 1)
without risking zero in the numerator and/or denominator, but I
haven't figured one out. [...]
I'm not sure why you need this ratio, but it's trivial to calculate...
(UINT_MAX/2+1) / (UCHAR_MAX/2+1)
<Self-administers a dope slap> Duhh ...
The ratio was to be used to solve the problem posed
(oh, so long ago) at the beginning of this thread: Write
fully portable code to left-adjust an `unsigned char' in
an `unsigned int'. Everybody (self included) got caught
up in trying to come up with a recipe using shifts, and
ran afoul of one or more of padding bits, shift counts too
wide for shifted operand, or uncommon relationships among
the various Uxxx_MAX values. The correct solutions offered
thus far involve ugly loops; "ugly" because they perform
a calculation at run time that any particular compiler
could have done during compilation.
Having the ratio available makes the problem easy:
unsigned char uc = ...;
unsigned int ui = uc
* ((UINT_MAX/2+1)/(UCHAR_MAX/2+1));
"Mainstream" implementations will calculate the ratio
as 2**N (N >= 1) and probably replace the multiplication
with a shift, while "exotic" implementations will get a
ratio of unity and probably eliminate the multiplication
altogether.