Concept behind these four lines of tricky C code

前端 未结 9 809
一向
一向 2020-12-22 14:40

Why does this code give the output C++Sucks? What is the concept behind it?

#include 

double m[] = {7709179928849219.0, 771};

i         


        
9条回答
  •  北海茫月
    2020-12-22 15:00

    The number 7709179928849219.0 has the following binary representation as a 64-bit double:

    01000011 00111011 01100011 01110101 01010011 00101011 00101011 01000011
    +^^^^^^^ ^^^^---- -------- -------- -------- -------- -------- --------
    

    + shows the position of the sign; ^ of the exponent, and - of the mantissa (i.e. the value without the exponent).

    Since the representation uses binary exponent and mantissa, doubling the number increments the exponent by one. Your program does it precisely 771 times, so the exponent which started at 1075 (decimal representation of 10000110011) becomes 1075 + 771 = 1846 at the end; binary representation of 1846 is 11100110110. The resultant pattern looks like this:

    01110011 01101011 01100011 01110101 01010011 00101011 00101011 01000011
    -------- -------- -------- -------- -------- -------- -------- --------
    0x73 's' 0x6B 'k' 0x63 'c' 0x75 'u' 0x53 'S' 0x2B '+' 0x2B '+' 0x43 'C'
    

    This pattern corresponds to the string that you see printed, only backwards. At the same time, the second element of the array becomes zero, providing null terminator, making the string suitable for passing to printf().

提交回复
热议问题