[英]IEEE-754 floating number binary represent
I'm solving a question on online judge: https://acm.cs.nthu.edu.tw/problem/12237/我正在解决一个在线法官的问题: https://acm.cs.nthu.edu.tw/problem/12237/
I need to represent IEEE-754 floating number with binary represent.我需要用二进制表示来表示 IEEE-754 浮点数。
Here's my code:这是我的代码:
#include <stdio.h>
void binaryprint();
int main(){
float x;
while(scanf("%f",&x) != EOF){ //File end with EOF
unsigned int y = *(unsigned int*)&x;
if(x == 0){ // INput = 0 -> 0*32
for(int i = 0 ; i < 32 ; i++){
printf("%d",0);
}
}
else {
if(x > 0) printf("%d",0); //0 means positive but I find c will not print it out
binaryprint(y); //transfer to binary represent
}
printf("\n");
}
}
void binaryprint(unsigned int x){
if(x != 1){
binaryprint(x/2);
printf("%d",x%2);
}
else{
printf("%d",1);
}
}
But I got few wrong answer and because of I didn't know the testcase, I can't find out if there's any exception lead to the wrong answer.但是我得到的错误答案很少,而且由于我不知道测试用例,我无法找出是否有任何异常导致错误答案。 Thanks for your help!谢谢你的帮助!
Here is a some program, with explanations in comments, that handles the cases shown.这是一个处理所示案例的一些程序,在注释中有解释。 (It does not handle infinities or NaNs.) (它不处理无穷大或 NaN。)
#include <math.h>
#include <stdio.h>
int main(void)
{
float x;
while (scanf("%f", &x) == 1)
{
// Print the sign bit.
putchar('0' + (x < 0));
if (x < 0)
x = -x;
/* Multiply or divide x by two to get a significand in the interval
[1, 2). At the same time, count the operations to figure what
power of two (in Exponent) is needed to scale that significand to
the original value of x.
*/
int Exponent = 0;
while (x < 1)
{
Exponent -= 1;
// If we reach the subnormal range, stop.
if (Exponent < -126)
break;
x *= 2;
}
while (2 <= x)
{
Exponent += 1;
x /= 2;
}
/* Encode the exponent by adding the bias of the IEEE-754 binary32
format.
*/
Exponent += 127;
// Print the seven bits of the exponent encoding.
for (int i = 7; 0 <= i; --i)
putchar('0' + (Exponent >> i & 1));
/* Skip the leading bit of the significand and print the 23 trailing
bits.
*/
x -= (int) x;
for (int i = 0; i < 23; ++i)
{
x *= 2;
int bit = x;
x -= bit;
putchar('0' + bit);
}
putchar('\n');
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.