fork download
  1. #include<stdio.h>
  2. #include <string.h>
  3.  
  4. /** copy the bytes at data directly into a double.
  5.   and return that.
  6. */
  7. double directValue(const char *data)
  8. {
  9. double result;
  10. char *dest = (char *)&result;
  11.  
  12. memcpy(dest, data, sizeof(double));
  13.  
  14. return result;
  15. }
  16.  
  17. /** copy the bytes at data into a double, reversing the
  18.   byte order, and return that.
  19. */
  20. double reverseValue(const char *data)
  21. {
  22. double result;
  23.  
  24. char *dest = (char *)&result;
  25.  
  26. for(int i=0; i<sizeof(double); i++)
  27. {
  28. dest[i] = data[sizeof(double)-i-1];
  29. }
  30. return result;
  31. }
  32.  
  33. /** Adjust the byte order from network to host.
  34.   On a big endian machine this is a NOP.
  35. There is no error handling
  36. */
  37. double ntohd(double src)
  38. {
  39. # if !defined(__FLOAT_WORD_ORDER__) \
  40. || !defined(__ORDER_LITTLE_ENDIAN__)
  41. # error "oops: unknown byte order"
  42. # endif
  43.  
  44. # if __FLOAT_WORD_ORDER__ == __ORDER_LITTLE_ENDIAN__
  45. return reverseValue((char *)&src);
  46. # else
  47. return src;
  48. # endif
  49. }
  50.  
  51. int main()
  52. {
  53. // big endian, i.e. network byte order
  54. const char onedotsomethingbytes[]
  55. = {0x3F, 0xF3, 0xC0, 0xCA, 0x42, 0x83, 0xDE, 0x1B};
  56.  
  57. double directDbl = directValue(onedotsomethingbytes);
  58. // on a big endian machine this would print 0.12345...
  59. printf("direct: %le\n", directDbl);
  60.  
  61. // on a little endian machine *this* would print 0.12345...
  62. printf("reverse: %le\n", reverseValue(onedotsomethingbytes));
  63.  
  64. // Use the double's memory as data. This is equivalent to using
  65. // the char array. It's also legal.
  66. printf("reverse: %le\n", reverseValue((char *)&directDbl));
  67.  
  68. // Try the ntohd with compile time decision.
  69. printf("ntohd: %le\n", ntohd(directDbl));
  70.  
  71. return 0;
  72. }
Success #stdin #stdout 0s 2156KB
stdin
Standard input is empty
stdout
direct:   1.927630e-174
reverse:  1.234568e+00
reverse:  1.234568e+00
ntohd:    1.234568e+00