Yes, there is a difference. Consider if one of the char
's has the value of -1
. When you do
(unsigned int)(unsigned char)-1
you get 255
for a 8 bit char
since you first do the conversion modulo 2^8
. If you instead used
(unsigned int)-1
then you would get 4294967295
for a 32 bit int
since you are now doing the conversion modulo 2^32
.
So the first cast guarantees the result will be representable in 8 bits, or whatever the actual size a char is, and then the second cast is to promote it to a wider type.
You can get rid of the casts to unsigned char
if you chnage the function parameters to it like
constexpr unsigned int foo(unsigned char ch0, unsigned char ch1,
unsigned char ch2, unsigned char ch3)
{
return static_cast<unsigned int>(ch0)
| static_cast<unsigned int>(ch1) << 8)
| static_cast<unsigned int>(ch2) << 16)
| static_cast<unsigned int>(ch3) << 24))
;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…