Guest User

Untitled

a guest
Nov 21st, 2017
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.96 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5.  
  6. typedef struct Binary {
  7. char sign;
  8. char exp[12];
  9. char precision[53];
  10. } Binary;
  11.  
  12.  
  13. // For transform the double to binary
  14. Binary *dtob(double a) {
  15. long num = *(long *)&a;
  16.  
  17. const int len = 64;
  18. char binary[len + 1];
  19. binary[64] = '\0';
  20. for (int i = 0; i < len; ++i) {
  21. binary[i] = (num & 1L) + '0';
  22. num >>= 1;
  23. }
  24.  
  25.  
  26. Binary *bin = (Binary *)malloc(sizeof(Binary));
  27. int i = 0, j = len - 1;
  28. while (i < j) {
  29. char temp = binary[i];
  30. binary[i] = binary[j];
  31. binary[j] = temp;
  32.  
  33. i += 1;
  34. j -= 1;
  35. }
  36.  
  37. bin->sign = binary[0];
  38. strncpy(bin->exp, binary + 1, 11);
  39. strcpy(bin->precision, binary + 12);
  40. return bin;
  41. }
  42.  
  43. void getBinary(Binary *bin) {
  44. printf("Sign: %c\n", bin->sign);
  45. printf("Exp: %s\n", bin->exp);
  46. printf("Precision: %s\n", bin->precision);
  47. }
  48.  
  49. int main () {
  50. double f;
  51.  
  52. puts("输入你要转化成二进制的浮点数");
  53. scanf("%lf", &f);
  54. getBinary(dtob(f));
  55. }
Add Comment
Please, Sign In to add comment