V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
liaofeng
V2EX  ›  C

c语言:float转换为short怎么计算?

  •  
  •   liaofeng · Apr 30, 2012 · 3249 views
    This topic created in 5121 days ago, the information mentioned may be changed or developed.
    今天翻了翻斯坦福大学的programming paradigms公开课,
    lecture 1讲c的数据结构。

    其中老师举例:
    float f = 7.0;
    short s = f;
    printf("s=%d\n", s);
    结果是:s=7。
    假设short占2字节,float占4字节,赋值的时候简单的做了一个截断,所以结果为7(但其实bit pattern还是经过了重新计算)。

    然后:
    float f = 7.0;
    short s = *(short *) &f;
    printf("s=%d\n", s);

    分析:*(short *) &f 是说赋值的时候将f视为short类型,所以*(short *)&f只能取到f的前两个字节。结果就变成了f前两个字节存储的是什么。
    根据float的表现方式:(-1)*2^0 * (1.xxxx)*2^(exp-127)
    7.0 = 3.5 * 2 = 1.75 * 2^2
    所以exp=129, s=0, 即前9位是0 10000001,结果不可能为0啊

    知道怎么回事么?
    2 replies    1970-01-01 08:00:00 +08:00
    liaofeng
        1
    liaofeng  
    OP
       Apr 30, 2012
    乃们怎么光看不回复啊?
    莫非就没有一个尚记得计算机基础知识的老鸟。。。
    013231
        2
    013231  
       Apr 30, 2012   ❤️ 3
    小端(little-endian)機器中, 數字的低位在低位地址上. float 7在內存中表示位00 00 e0 40,
    short s = *(short *) &f;
    取其低二位, 故爲0.
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3035 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 13:26 · PVG 21:26 · LAX 06:26 · JFK 09:26
    ♥ Do have faith in what you're doing.