2016-08-24 8 views
2

など。整数7を浮動小数点0.111に変換するにはどうすればよいですか?ベース10の0から1の間の分数の2進整数、C

素朴な方法は、文字列1117を変換する整数111にそれを変換し0.111を取得するために1000で割ることであろう。しかし、より良い/より速い方法はありますか?

実例があります。

#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); 

} 
+1

なぜこのようにしていますか?奇妙な変換に見えます。 3> 3221225471(0.11> 0.10111111111111111111111111111111)および2 = 1(0.10 = 0.1)である。 – Ray

+0

浮動小数点値を表現するのに奇妙な構造が使用されていると思います。 – jxh

+0

@レイ元の動機は[このようなSobolシーケンスを構築する]ことです(http://www.americanscientist.org/include/popup_fullImage.aspx?key=mAGyoWpHKxq4DbGJIaAyrUVGvdPDqRmPFA5WsU8dgjqivkZFgKQb4A?)、私は間違いを犯しました。それは実際に助けてくれません! (私は思う。)いつか誰かを助けてくれることをうまくいけばいい。 –

答えて

3

文字列に変換する必要はありません。 Cはこの目的のためにうまく動作するバイナリ演算子を持っています。

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

しかし、' 0.0101'が欲しいのですが?実際には、この質問はOP –

+0

です。@ユージーン:そうです、問題のOPはそのシナリオを可能にしません。入力が既に正規化されているようです。 – jxh

+1

したがって、問題文は「* 0.1 *と* 0.111(1)*の間で分数をとる2進整数」になります。 –

関連する問題