htons.c 380 B

123456789101112131415161718192021222324
  1. /* $OpenBSD: htons.c,v 1.9 2014/12/20 18:15:29 miod Exp $ */
  2. /*
  3. * Written by J.T. Conklin <jtc@netbsd.org>.
  4. * Public domain.
  5. */
  6. #include <sys/types.h>
  7. #include <sys/endian.h>
  8. #undef htons
  9. u_int16_t htons(u_int16_t);
  10. u_int16_t
  11. htons(u_int16_t x)
  12. {
  13. #if BYTE_ORDER == LITTLE_ENDIAN
  14. u_char *s = (u_char *) &x;
  15. return (u_int16_t)(s[0] << 8 | s[1]);
  16. #else
  17. return x;
  18. #endif
  19. }