简体   繁体   中英

Cast char to int by zero extending in C++

I want to write a function

int char_to_int(char c);

that converts given char to int by zero extending the value. So if the char has N bits and int has M bits, M >= N, then the MN most significant bits of the int value should be zero and the N least significant bits of the int value should match the bits of the char value.

This seems like a simple task, but I'm not sure how to write it relying only on standard behavior. No UB, no implementation-defined behavior. Without relying on char being 8 bit, int being 32 bit, char being unsigned and any other common assumptions I make that are not guaranteed by standard.

The reason I want to know this, is that I have done this conversion several times in the past, but recently I became aware about the limited guarantees C++ gives about it's data types. So now I'm curious what is the correct, standard compliant approach.

I don't suppose

return (int) c;

is good enough, is it?

There's no hurt in being extra clear:

return int((unsigned char)c);

That way you tell the compiler exactly what you want: the int that contains the char value, read as unsigned. So char 255 will become int 255.

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