简体   繁体   中英

How to initialize a signed char to unsigned values like 0xFF in C++?

There are some cases where a byte array is implemented in a library using a char type, which is a signed type for many compilers.

Is there a simple, readable and correct way to initialize a signed char with a hex value which is greater than 127 and not bigger than 255?

Currently I end up with the following, and I keep thinking that there must be something simpler:

const unsigned char ff_unsigned = 0xff;
const char ff_signed = static_cast<const char>(ff_unsigned);

I want a solution with no warnings, even when using higher compiler warning levels than the default.

The following solution eg creates C4310: cast truncates constant value with MSVC 2013:

const char ff_signed = char(0xff);

Yes there is. Use single quotation characters with \\x as the prefix. That denotes a hexadecimal literal char type.

For example: '\\xff' .

But note that char can be signed or unsigned and up to and including C++11 it can even be a 1's complement signed type.

const char ff_unsigned = '\xff';

0xff is an int and '\\xff' is a char.`You can use

const char ff_signed = (char)0xff;

or

const char ff_signed = '\xff';

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