【问题标题】:Binary integer to fraction between 0 and 1 in base 10, in C二进制整数到以 10 为底的 0 和 1 之间的分数,在 C 中
【发布时间】:2016-08-24 19:33:21
【问题描述】:

例如。如何将整数 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);

}

【问题讨论】:

  • 出于好奇,你为什么要这样做?考虑到在它之下,这似乎是一个奇怪的转换,例如3 > 3221225471 (0.11 > 0.10111111111111111111111111111111) 和 2 = 1 (0.10 = .1)。
  • 我想有一个奇怪的结构被用来表示一个浮点值。
  • @Ray 所以最初的动机是construct a Sobol sequence like this,但我犯了错误,这个问题实际上并没有帮助! (我想。)希望有一天它对某人有所帮助。
  • 啊,这更有意义。 jxh的解决方法,基本上还是对的;您只需要以相反的方向循环这些位即可反转序列。 for (int bit = CHAR_BIT * sizeof(unsigned) - 1; bit &gt;= 0; bit--) { x += (input &gt;&gt; bit) &amp; 1; x /= 10.0; }

标签: c binary


【解决方案1】:

你不需要转换成字符串。 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.10.111(1) 之间的分数”。
  • @EugeneSh.:嗯,0 是可能的。
  • 是的。这让我对这种奇怪转换的应用感到好奇
猜你喜欢
  • 1970-01-01
  • 2012-04-28
  • 2014-07-26
  • 2018-07-12
  • 2017-07-19
  • 2016-04-23
  • 1970-01-01
  • 2017-01-03
  • 2020-12-11
相关资源
最近更新 更多