【问题标题】:How to output hex value from function that takes float inputs如何从采用浮点输入的函数中输出十六进制值
【发布时间】:2021-05-18 17:19:53
【问题描述】:

根据给出的一些建议,我编辑了代码以显示以下内容。

#include <stdio.h>
#include <stdlib.h>

//function declaration
unsigned char float_to_hex(float value);


int main()
{
unsigned char hex_value=0x00;

//variable that stores returned hex value
hex_value = float_to_hex(1.0);
printf("The hex value is %x\n", hex_value);

return 0;
}



// Function definition
unsigned char float_to_hex(float value)
{
float atten_float=0.0;
unsigned char atten_hex=0x00;

if( atten_float == 0.0)
{
    atten_hex = 0x00;
    return atten_hex;
}
else if (atten_float== 0.5)
{
  atten_hex = 0x01;
  return atten_hex;


}
else if (atten_float == 1.0)
{
    atten_hex = 0x02;
    return atten_hex;

}
else
{
    atten_hex = 0x00;
    return atten_hex;

}
return -1;

    }

我通过在函数定义中本地初始化变量来编辑代码。另外,我正在使用“%x”来打印“hex_value”的十六进制值,但是,我仍然得到相同的结果,即 0。

【问题讨论】:

    标签: c if-statement hex return-value


    【解决方案1】:

    您通过使用可与register 说明符atten_float 一起使用的非静态局部变量的值调用了未定义的行为。在使用变量中的值之前,您必须将其初始化为某个值。

    atten_float == 0.0 的情况下,atten_hex 也无需初始化即可使用。你应该在那里添加初始化。

    最后,您可能希望使用%x 而不是%c 来打印十六进制值。

    #include <stdio.h>
    #include <stdlib.h>
    
    //function declaration
    unsigned char float_to_hex(float value);
    
    
    int main()
    {
        unsigned char hex_value;
    
        //variable that stores returned hex value
        hex_value = float_to_hex(1.0);
        printf("The hex value is %x\n", hex_value); /* use %x instead of %c */
    
        return 0;
    }
    
    
    
    // Function definition
    unsigned char float_to_hex(float value)
    {
        float atten_float = value; /* add initialization */
        unsigned char atten_hex;
    
        if( atten_float == 0.0)
        {
            atten_hex = 0x42; /* add initialization */
            return atten_hex;
        }
        else if (atten_float== 0.5)
        {
            atten_hex = 0x01;
            return atten_hex;
    
        }
        else if (atten_float == 1.0)
        {
            atten_hex = 0x02;
            return atten_hex;
        }
        else
        {
            atten_hex = 0x00;
            return atten_hex;
        }
        return -1;
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-18
      • 1970-01-01
      • 2011-12-05
      • 2012-03-13
      相关资源
      最近更新 更多