Why, when casting a short [] to char *, the array is canceled?

For the following code:

short shortArray [] = { ( 'B' << 8 ) + 'A', ( 'D' << 8 ) + 'C', ( 'F' << 8 ) + 
'E', 'G' };
cout << (char*)shortArray;

Conclusion:

ABVGDEZH

Can someone explain to me how this works?

+4
source share
2 answers

Short is 16 bits, and char is 8. Thus, one short can contain two characters.

The part ( 'B' << 8 ) + 'A'shifts the value of β€œB” by 8 bits and adds it to A. So, now each half of the short circuit contains the ASCII code of another character. In this case, A and B.

Now, going to char *, it will interpret the array as a string (this is just an array of characters), and you get this output

+4
source

The expression ( 'B' << 8 ) + 'A'has a result of the type intwill be equal 'B'*256 + 'A'.

short ( , short 8- ) AB, A . (.. 'A' , 'B'). , 'B' .

, , , .

Intel - . , CPUS, Motorola 68000, PowerPC Sparc ( Sun Microsystems), . ( ) .

: , , , undefined. <<, a char * char '\0'. .

+4

Source: https://habr.com/ru/post/1692510/


All Articles