Skip to content

Instantly share code, notes, and snippets.

@thoamsy
Last active October 4, 2018 13:55
Show Gist options
  • Save thoamsy/28b278a098d0daeb495c8dbeca40cc1a to your computer and use it in GitHub Desktop.
Save thoamsy/28b278a098d0daeb495c8dbeca40cc1a to your computer and use it in GitHub Desktop.
C 语言实现的将 Double 转成二进制
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
typedef struct Binary {
char sign;
char exp[12];
char precision[53];
} Binary;
// For transform the double to binary
Binary *dtob(double a) {
long num = *(long *)&a;
const int len = 64;
char binary[len + 1];
binary[64] = '\0';
for (int i = 0; i < len; ++i) {
binary[i] = (num & 1L) + '0';
num >>= 1;
}
Binary *bin = (Binary *)malloc(sizeof(Binary));
// 首尾交换,因为是小端
int i = 0, j = len - 1;
while (i < j) {
char temp = binary[i];
binary[i] = binary[j];
binary[j] = temp;
i += 1;
j -= 1;
}
bin->sign = binary[0];
strncpy(bin->exp, binary + 1, 11);
strcpy(bin->precision, binary + 12);
return bin;
}
void getBinary(Binary *bin) {
printf("Sign: %c\n", bin->sign);
printf("Exp: %s\n", bin->exp);
printf("Precision: %s\n", bin->precision);
free(bin);
}
const double charToDouble(char *s) {
double left = 0;
double right = 0;
while (*s) {
if (*s >= '0' && *s <= '9') {
left = left * 10 + *s - '0';
}
if (*s == '.') {
s++;
break;
}
s++;
}
double base = 10.0;
while (*s) {
if (*s >= '0' && *s <= '9') {
right += (*s - '0') / base;
base *= 10;
}
s++;
}
return left + right;
}
void output(double f) {
printf("浮点数 %lf: \n", f);
getBinary(dtob(f));
puts("");
}
double create-nan() {
unsigned char *bits = calloc(sizeof(double), 1);
// 大部分人的电脑是小端,所以要从 6 和 7 开始,而不是 0 和 1
// 不清楚概念的可以参考阮老师:
// [理解字节序 - 阮一峰的网络日志](http://www.ruanyifeng.com/blog/2016/11/byte-order.html)
bits[6] = 255;
bits[7] = 255;
unsigned char *start = bits;
double nan = *(double *)(bits);
output(nan);
free(bits);
return nan;
}
int main (int args, char **argv) {
const double nan = sqrt(-2);
const double inf = 1.0 / 0;
const double ninf = -1.0 / 0;
while (*++argv) {
output(charToDouble(*argv));
}
output(nan);
output(inf);
output(ninf);
create-nan();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment