EG。如何将整数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);
}
答案 0 :(得分:3)
您无需转换为字符串。 C具有二进制运算符,可以很好地用于此目的。
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!
pod 'Kingfisher', '~> 2.4'