简体   繁体   中英

Portable conversion from unsigned to signed in C++

I have std::vector<unsigned short int> vals for which I need to invert the order of the bytes (assume 2) and store them as short int . I was doing it as:

std::vector<short int> result;
for(unsigned short int& x : vals) {
    x = ((x << 8) | (x >> 8));
    result.push_back(static_cast<short int>(x));
}

Reading online, I find that static_cast has implementation-defined behavior. I also found std::bit_cast , which preserves the bits and interprets them in the new type.

Does that mean that using std::bit_cast<short int>(x) above should be preferred over static_cast ?

I tried, and both give the same results for me. Is it correct to assume that bit_cast will give the same results to anyone else using my code, while static_cast could give them different results?

If you want to handle bytes - you should not convert them to a non byte type (especially not short int and friends because they does not need to be 16 bits exactly). You should read the bytes as an array of char or std::byte . Then you can swap those values in safe and portable manner. Converting those bytes to a numeric type is not doable in portable way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM