What happens when I convert int to char?

9

An integer has 4 bytes , whereas a char has only 1 byte .

When I make this definition:

int a = 1000; // 1111101000
char b = (char) a;

I think it will only take 1 byte of data, but what I want to know is whether it will pick up at the beginning or the end.

    
asked by anonymous 21.03.2014 / 21:30

4 answers

8

Considering that a int is 32 bits and a char is 8 bits. In this conversion you will only get bits 0 through 7 of your int .

If int storing 1000 is:

0000 0000 0000 0000 0000 0011 1110 1000 // equivale a 1000 em 32 bits
^                                     ^
32                                    0

Converting to char you only get:

1110 1000 // equivale a 232 em 8 bits
^       ^
7       0

So, the% w of% that stores 1000, when converted to int , results in 232.

    
21.03.2014 / 21:34
4

It will take the start byte, which in the human representation, are the least significant digits, ie the final digits.

I say this because in memory, the first byte is actually the least significant data, and the last is the most significant. While we human beings do the opposite.

Example:

0x12345678 <- representação humana

0x78, 0x56, 0x34, 0x12 <- ordenação dos bytes na memória do computador x86

As pointed out by @pmg, there are architectures in which this order of addresses is inverse to that placed above.

    
21.03.2014 / 21:33
2

Explicitly referencing the C standard (I used N

  

6 Language

     

6.3 Conversions

     

6.3.1 Arithmetic operands

     

6.3.1.3 Signed and unsigned integers

     

1 When an integer type is converted to another integer type other than _Bool , if the value can be represented by the new type, it is unchanged .

     Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type.

until the value is in the range of the new type.

     

3 Otherwise, the new type is signed and the value can not be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.

A brief translation:

1 - If the value can be represented in the target type, it will be. 2 - If they are unsigned will occur truncation of the bits. (as the other answers say). 3 - If they are signed , result is defined by implementation.

The third point is quite important. If you convert a int to a char it may have unexpected results from your compiler. Although virtually all truncate the bits, you should not assume that this always occurs.

Prefer to convert from unsigned int to unsigned char when possible.

    
22.03.2014 / 13:39
-1

What can happen in converting int to char is the conversion based on tabela ascii .

For example:

    
22.03.2014 / 01:52