联合的二进制表示

联合的二进制表示

本文介绍了联合的二进制表示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的程序中:

联合{国际我;浮动 f;你;

假设是 32 位编译器,u 在内存中分配了 4 个字节.

u.f = 3.14159f;

3.14159f 使用 IEEE 754 表示,在这 4 个字节中.

printf("作为整数:%08x\n", u.i);

u.i 在这里代表什么?IEEE 754 二进制表示是否被解释为 4 字节 signed int?

解决方案

i 读取是实现定义等等.

仍然.

在普通"平台上

  • float

    现在,有符号位会混淆 int 的 2 的补码表示,所以你可能想要使用 unsigned 类型来做这种实验.此外,memcpy 是执行类型双关的一种更安全的方式(您不会看到有关标准的肮脏外观和讨论),因此如果您执行以下操作:

    float x = 1234.5678;uint32_t x_u;memcpy(&x_u, &x, sizeof x_u);

    现在您可以轻松提取 FP 表示的各个部分:

    int sign = x_u>>31;//0 = 正;1 = 负int exponent = ((x_u>>23) & 0xff;//应用 -127 偏差来获得实际指数int 尾数 = x_u &~((无符号(-1)<

    (请注意,这完全忽略了所有神奇"模式 - 安静和发出信号的 NaN 和次正规数浮现在脑海中)

    In the below program:

    union
    {
      int i;
      float f;
    } u;
    

    Assuming 32 bit compiler, u is allocated with 4 bytes in memory.

    u.f = 3.14159f;
    

    3.14159f is represented using IEEE 754, in those 4 bytes.

    printf("As integer: %08x\n", u.i);
    

    What does u.i represent here? Is IEEE 754 binary representation interpreted as 4 byte signed int?

    解决方案

    Reading from i is implementation-defined blah blah blah.

    Still.

    On "normal" platforms where

    (AKA any "regular" PC with a recent enough compiler)

    you will get the integer whose bit pattern matches the one of your original float, which is described e.g. here

    Now, there's the sign bit that messes up stuff with the 2's complement representation of int, so you probably want to use an unsigned type to do this kind of experimentation. Also, memcpy is a safer way to perform type-punning (you won't get dirty looks and discussions about the standard), so if you do something like:

    float x = 1234.5678;
    uint32_t x_u;
    memcpy(&x_u, &x, sizeof x_u);
    

    Now you can easily extract the various parts of the FP representation:

    int sign     = x_u>>31;                    // 0 = positive; 1 = negative
    int exponent = ((x_u>>23) & 0xff;          // apply -127 bias to obtain actual exponent
    int mantissa = x_u & ~((unsigned(-1)<<23);
    

    (notice that this ignores completely all the "magic" patterns - quiet and signaling NaNs and subnormal numbers come to mind)

    这篇关于联合的二进制表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 18:15