Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
182 views
in Technique[技术] by (71.8m points)

c++ - Is it pointless to concatenate C-style cast operations?

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>?

question from:https://stackoverflow.com/questions/65836914/is-it-pointless-to-concatenate-c-style-cast-operations

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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))
           ;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...