When copying an int into a char variable, how is any excess data used?
I know that an int is 4 bytes and a char is 1 byte.
So there will be an extra 3 bytes unused.
When copying an int into a char variable, how is any excess data used?
I know that an int is 4 bytes and a char is 1 byte.
So there will be an extra 3 bytes unused.
Technically, it is undefined. Moving values that are OUTSIDE THE RANGE of the destination type is "undefined behaviour" by the C standard - the compiler (or generated code) can do whatever it likes in that situation - perform whatever operation makes sense, launch nuclear attack on country X, crash the computer, etc, etc.
If you do not aspire for super-portable code, we can however, with realistic likelyhood of no nuclear attacks etc, make the assumption that it is simply "lost" - the data that doesn't fit in the destination will be ignored.
E.g. 256 into a char will be 0 [assuming 8 bits per char]. 812 [again, with 8 bits] will give you the value 44, or ',' if the character set is ASCII.
--
Mats
Last edited by matsp; 05-06-2009 at 08:19 AM.
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
Look at this example in big-endian:
10001001 | 10111001 | 10000001 | 00110111 (32-bit integer, 2310635831 in decimal)
(10001001 | 10111001 | 10000001) 00110111 (8-bit char, 55 in decimal)
The bits in parentheses are sent to Nirwana since they don't fit into one byte. Of course, such low-level things may vary. That's why it's undefined. In little-endian, just reverse the order of bytes. It will do the same. In these cases, it's just like module 256. But don't rely on that - there are some other possibilities.
Last edited by Brafil; 05-06-2009 at 09:54 AM.
Obviously endian-ness doesn't matter for a simple assignment where the left-hand side is smaller than the right-hand side. If we are using pointers, then endian-ness WILL matter.
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
Then the remaining bits are still there, but not used. Although you can use them with a cast to int *.
Thank you for all your input ladies and gents!
The compiler will likely warn you of "lost data" or something to that effect if the programmer does no explicit casting.
The source and destinations should be the same size... and the programmer should cast things to that effect to alleviate the compiler warnings - so as to prove he/she knows what they're doing on purpose. You may very well want to truncate excess data.
I seriously doubt that any implementation of C would grab some non intuitive byte out of a multi-byte integer when forcing into a char. Sheesh. We sure have a lot of "ANSI Standard blah blah" people here. What are you?? On a committee, or are ya programmers? Undefined... gimme a break.