util.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. * Copyright (C) 2006 Michael Buesch <m@bues.ch>
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License version 2
  6. * as published by the Free Software Foundation.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. */
  13. #include "util.h"
  14. #include <stdio.h>
  15. #include <string.h>
  16. void dump(const char *data,
  17. size_t size,
  18. const char *description)
  19. {
  20. size_t i;
  21. char c;
  22. fprintf(stderr, "Data dump (%s, %zd bytes):",
  23. description, size);
  24. for (i = 0; i < size; i++) {
  25. c = data[i];
  26. if (i % 8 == 0) {
  27. fprintf(stderr, "\n0x%08zx: 0x%02x, ",
  28. i, c & 0xff);
  29. } else
  30. fprintf(stderr, "0x%02x, ", c & 0xff);
  31. }
  32. fprintf(stderr, "\n");
  33. }
  34. void * xmalloc(size_t size)
  35. {
  36. void *p;
  37. p = malloc(size);
  38. if (!p) {
  39. fprintf(stderr, "Out of memory\n");
  40. exit(1);
  41. }
  42. memset(p, 0, size);
  43. return p;
  44. }
  45. char * xstrdup(const char *str)
  46. {
  47. char *c;
  48. c = strdup(str);
  49. if (!c) {
  50. fprintf(stderr, "Out of memory\n");
  51. exit(1);
  52. }
  53. return c;
  54. }
  55. be16_t cpu_to_be16(uint16_t x)
  56. {
  57. be16_t ret;
  58. uint8_t *tmp = (uint8_t *)(&ret);
  59. tmp[0] = (x & 0xFF00) >> 8;
  60. tmp[1] = (x & 0x00FF);
  61. return ret;
  62. }
  63. be32_t cpu_to_be32(uint32_t x)
  64. {
  65. be32_t ret;
  66. uint8_t *tmp = (uint8_t *)(&ret);
  67. tmp[0] = (x & 0xFF000000) >> 24;
  68. tmp[1] = (x & 0x00FF0000) >> 16;
  69. tmp[2] = (x & 0x0000FF00) >> 8;
  70. tmp[3] = (x & 0x000000FF);
  71. return ret;
  72. }