Diego Alonso Cortez - 2 years ago 95
C Question

Binary integer to fraction between 0 and 1 in base 10, in C

Eg. how can I transform the integer

`7`
to the float
`0.111`
?

The naive way would be to convert
`7`
to the string
`111`
, convert that to the integer
`111`
and then divide by 1000 to get
`0.111`
. Is there a better/faster way, though?

Here's a working example.

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

}
``````

You don't need to convert into a string. C has binary operators that work just fine for this purpose.

``````double binary_inverse (unsigned input) {
double x = 0;
while (input) {
x += input & 0x1;
x /= 10;
input >>= 1;
}
return x;
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download