9

In the walkthrough example, ASCII-0.c, a cast has been performed to convert a number (integer in specific) to a character.

I would like to know what exactly happens at the lower level when we cast an int to a char, or in general, from one data type to another.

8

Lets say you have the following code:

short myShort = 23948;
byte myByte = (byte)myShort;

mybyte will contain the value 140. Short is a 2-byte type and a byte is a single byte. When you cast from two bytes to one you're forcing the system to make things fit and one of the original bytes (the most significant) gets dropped and data is lost. What is left from the value of 23948 (binary: 0101 1101 1000 1100) is 140 which in binary translates to 1000 1100. So you are going from:

0101 1101 1000 1100 (2 byte decimal value 23948) 

to

1000 1100 (1 byte decimal value 140)

You can only do this with an explicit cast. If you tried assigning a short to a byte without a cast the compiler would throw an error because of the potential for loss of data. If you are casting from a 2 byte to a 4 byte data type for instance, it is vice-versa, i.e. the system will have to allocate more memory for the additional bits.

0

Variables are stored into memory as strings of bits.

The type of a variable can modify the way the variable is stored into memory: ex, the value 3 (as an integer) and 3.0 (as a float) have a different representation in memory.

Chars are represented using their ASCII values (a -> 65, b -> 66 and so on). A char is usually 8-bits long, while an integer can be 8, 16, 32 or 634 bits.

Casting an int to a char, or a float to an int, modifies its internal representation, so that your code will be able to "use" it in the correct mode.

On 32-bit operating systems, a value represented with 32 bits is "squeezed" into an 8-bit variable: if the value of the int was less than 256, the cast just eliminates the leading zeroes of the number, else the number is truncated.

1
  • I think really what the asker is looking for is like specifics, like @CodeFactz answer provides. Really what casting does is truncating mainly (I.e. Int -> Byte cuts off most significant 3 bits). – lijrobert Jun 9 '14 at 2:41

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .