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
644 views
in Technique[技术] by (71.8m points)

variables - C- why char c=129 will convert into -127?

if we assign +128 to char variable then it is converted into -128 because of binary equivalent(10000000-first bit tells sign). Binary equivalent of 129 is 10000001, What will be the value it will be converted to?

char c=129;

Thanks, S

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

There are actually several possibilities.

If char is a signed type, then

char c = 129;

implicitly converts the int value to char. The result is implementation-defined (or it can raise an implementation-defined signal, but I don't know of any implementations that do that). In most implementations, the conversion yields -127 because signed types are represented using two's-complement. In an unsigned 8-bit type, 10000001 represents the value 129; in a signed 8-bit type, the same bit pattern represents -127; the conversion isn't required to keep the same bit pattern, but it very commonly does.

If plain char is an unsigned type (as it is on some systems), then the value 129 is within the range of char, and the conversion simply yields the value 129.

But all this assumes that char is 8 bits. The C standard requires CHAR_BIT (the number of bits in a byte, or equivalently in a char object) to be at least 8, but it permits it to be larger. You're not likely to run into a system with CHAR_BIT > 8, but it's not uncommon in C implementations for DSPs.

Depending on all this is rarely a good idea. Whatever it is you're trying to accomplish by assigning 129 to a char object, there's very likely a better, clearer, and more portable way to do it.


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

...