二进制整数到小数(以10为基数,以C为单位,介于0和1之间)

二进制整数到小数(以10为基数,以C为单位,介于0和1之间),c,binary,C,Binary,如何将整数7转换为浮点0.111 最简单的方法是将7转换为字符串111,将其转换为整数111,然后除以1000得到0.111。但是,有更好/更快的方法吗 这里有一个有效的例子 #include <stdio.h> #include <stdint.h> #include <stdlib.h> // Convert 32-bit uint to string // http://stackoverflow.com/questions/699968/displa

如何将整数
7
转换为浮点
0.111

最简单的方法是将
7
转换为字符串
111
,将其转换为整数
111
,然后除以1000得到
0.111
。但是,有更好/更快的方法吗

这里有一个有效的例子

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

// Convert 32-bit uint to string
// http://stackoverflow.com/questions/699968/display-the-binary-representation-of-a-number-in-c
const char* bin(uint32_t n){
    uint N = 32;
    static unsigned char ucharBuffer[32+1];
    char *p_buffer = ucharBuffer;

    if(!n)
        return "0";

    // Work from the end of the buffer back
    p_buffer += N;
    *p_buffer-- = '\0';

    //For each bit (going backwards) store character
    while(n){
        if (N-- == 0)
            return NULL;
        *p_buffer-- = ((n & 1) == 1) ? '1' : '0';
        n >>= 1;}

    return p_buffer+1;}


int main(){

    uint INPUT = 7;
    const char *p = bin(INPUT);
    char *end;

    printf("%d -> ", INPUT);
    printf("'%.*s' -> ", (uint)(end-p), p);
    printf("%.3f\n", (double) strtol(p, &end, 10)/1000);

}
#包括
#包括
#包括
//将32位uint转换为字符串
// http://stackoverflow.com/questions/699968/display-the-binary-representation-of-a-number-in-c
常量字符*bin(uint32\u t n){
uint N=32;
静态无符号字符ucharBuffer[32+1];
char*p_buffer=ucharBuffer;
如果(!n)
返回“0”;
//从缓冲区的末端向后工作
p_缓冲区+=N;
*p_缓冲区--='\0';
//对于每个位(向后)存储字符
while(n){
如果(N-->=0)
返回NULL;
*p_缓冲区--=((n&1)==1)?“1”:“0”;
n>>=1;}
返回p_缓冲区+1;}
int main(){
uint输入=7;
常量字符*p=bin(输入);
字符*结束;
printf(“%d->”,输入);
printf(“'%.*s'->”,(uint)(p端),p);
printf(“%.3f\n”,(双)strtol(p,&end,10)/1000);
}

您不需要转换为字符串。C有二进制运算符,可以很好地用于此目的

double binary_inverse (unsigned input) {
    double x = 0;
    while (input) {
        x += input & 0x1;
        x /= 10;
        input >>= 1;
    }
    return x;
}

但是如果我们想要
0.0101
?其实这个问题是给OP@EugeneSh.:是的,OP的问题并不能使这种情况成为可能。似乎输入已经规范化了。所以问题陈述应该是“0.1到0.111(1)之间的二进制整数到分数”。@EugeneSh.:哦,0是可能的。是的。这让我想知道,出于好奇,你为什么要这样做?这似乎是一个奇怪的转换,因为在它下面,例如3>3221225471(0.11>0.10111111111111)和2=1(0.10=.1)。我想象有一个奇怪的结构被用来表示浮点值。@Ray所以最初的动机是这样,但我犯了一个错误,这个问题实际上没有帮助!(我想)希望有一天它能帮助某人。啊,这更有意义。jxh的解决方案基本上仍然是正确的方法;您只需要在相反方向上循环位,以反转序列<代码>用于(int bit=CHAR\u bit*sizeof(unsigned)-1;bit>=0;bit--){x+=(输入>>位)&1;x/=10.0;}