Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...