int to char

Started by
4 comments, last by a light breeze 5 months, 1 week ago

Let's say you convert an int to a char in C++ like this:

int i = -1;
char c = i;

What exactly happens from a bit perspective? Does it just assign the lowest 8 bits of the 32-bit int?

It's not obvious to me that this will work for negative numbers.

Thank you.

Mike C.http://www.coolgroups.com/zoomer/http://www.coolgroups.com/ez/
Advertisement

mike74 said:
It's not obvious to me that this will work for negative numbers.

Did you try attach a debugger and see for yourself?

The other part of the answer is, defined by the standard: If the conversion is between same-signed types, and the value fits into the range of the smaller type, that's what you get. So in your case, the result would be “-1”. If the value is too large to actually fit into the smaller typ, this behaviour is implementation-defined, meaning it's up to the compiler to decide what's the appropriate action to take. Typically, you will get truncation. meaning that bytes that don't fit into the smaller type are discarded. But there is no guarantee.

It is obvious to me that it will work on negative numbers (assuming 2's complement representation), and it's easy enough to verify that it does if it's not obvious to you. (Hint: the 2's complement representation of -1 is “all bits set to 1”, however many bits there are. Truncate 32 bits all set to 1 to 8 bits, and you'll get 8 bits all set to 1.)

@a light breeze It's obvious that it works for negative one, but is it really obvious that it works for all the negative numbers?

Mike C.http://www.coolgroups.com/zoomer/http://www.coolgroups.com/ez/

@mike74 For all the questions that you ask on details of what to expect, the C and C++ standards have the answer. Read the cppreference site.

The text is dense though, it takes time to understand how to read such text.

mike74 said:

@a light breeze It's obvious that it works for negative one, but is it really obvious that it works for all the negative numbers?

Yes?

The representation of -2 is “rightmost bit set to 0, all others set to 1”. The representation of -3 is “second-to-rightmost bit set to 0, all others set to 1”. The representation of -4 is “rightmost and second-to-rightmost bits set to 0, all others set to 1". The general pattern is that all 8-bit negative numbers can be expanded to 32 bits by filling in the missing bits with 1, just like all non-negative 8-bit negative numbers can be expanded to 32 bits by filling in the missing bits with 0. It follows that so long as the number fits in the range of an 8-bit signed integer, converting in the other direction only requires truncating the leftmost 24 bits (which will all be 1 for negative values and 0 for non-negative values).

This topic is closed to new replies.

Advertisement