3

At work I found this code in my codebase, where chars are casted twice:

constexpr unsigned int foo(char ch0, char ch1, char ch2, char ch3)
{
    return   ((unsigned int)(unsigned char)(ch0) 
           | ((unsigned int)(unsigned char)(ch1) << 8)
           | ((unsigned int)(unsigned char)(ch2) << 16) 
           | ((unsigned int)(unsigned char)(ch3) << 24))
           ;
}

Wouldn't one cast to unsigned int be sufficient?
And in that case better make it a static_cast<unsigned_int>?

3
  • 1
    Fun fact: The only thing making this C++ is constexpr. The rest is C style casts.
    – Ted Lyngmo
    Jan 21, 2021 at 22:51
  • 2
    Hint: char is a signed type on many platforms. Consider what happens when ch0 is -1. Jan 21, 2021 at 22:52
  • 1
    Unrelated: Try to avoid the C-Style casts. They ignore all common sense and will force the conversion no matter how bad an idea. A static_cast is a better choice here because if you do screw up, the compiler can catch the mistake. Jan 21, 2021 at 22:52

1 Answer 1

11

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))
           ;
}
2
  • Thank you. I had not thought about that. In my head casting char to int would've preserved the 8-bit value but I can see that would not have been the case.
    – Turambar
    Jan 21, 2021 at 23:07
  • @Turambar yes, when extending a smaller numeric type to a larger numeric type, you have to pay attention to sign-extension vs zero-extension. This kind of code requires zero-extension. Jan 22, 2021 at 4:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.