【发布时间】: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 >= 0; bit--) { x += (input >> bit) & 1; x /= 10.0; }