Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.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);
- }
- int main () {
- double f;
- puts("输入你要转化成二进制的浮点数");
- scanf("%lf", &f);
- getBinary(dtob(f));
- }
Add Comment
Please, Sign In to add comment