number_pack.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /* Copyright (C) 2016 Jeremiah Orians
  2. * This file is part of M2-Planet.
  3. *
  4. * M2-Planet is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation, either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * M2-Planet is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with M2-Planet. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. #include<stdlib.h>
  18. #include<string.h>
  19. #include<stdio.h>
  20. // void* calloc(int count, int size);
  21. int hex2char(int c);
  22. void file_print(char* s, FILE* f);
  23. void require(int bool, char* error);
  24. char* number_to_hex(int a, int bytes)
  25. {
  26. require(bytes > 0, "number to hex must have a positive number of bytes greater than zero\n");
  27. char* result = calloc(1 + (bytes << 1), sizeof(char));
  28. if(NULL == result)
  29. {
  30. file_print("calloc failed in number_to_hex\n", stderr);
  31. exit(EXIT_FAILURE);
  32. }
  33. int i = 0;
  34. int divisor = (bytes << 3);
  35. require(divisor > 0, "unexpected wrap around in number_to_hex\n");
  36. /* Simply collect numbers until divisor is gone */
  37. while(0 != divisor)
  38. {
  39. divisor = divisor - 4;
  40. result[i] = hex2char((a >> divisor) & 0xF);
  41. i = i + 1;
  42. }
  43. return result;
  44. }