b64dump.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*====================================================================*
  2. *
  3. * size_t b64dump (void const * memory, size_t extent, size_t column, FILE *fp);
  4. *
  5. * base64.h
  6. *
  7. * base64 encode a memory region and write to a text file; wrap
  8. * the output at a given column; do not wrap when column is 0;
  9. *
  10. * Motley Tools by Charles Maier;
  11. * Copyright (c) 2001-2006 by Charles Maier Associates;
  12. * Licensed under the Internet Software Consortium License;
  13. *
  14. *--------------------------------------------------------------------*/
  15. #ifndef B64DUMP_SOURCE
  16. #define B64DUMP_SOURCE
  17. #include <stdio.h>
  18. #include <stdint.h>
  19. #include "../tools/base64.h"
  20. #include "../tools/types.h"
  21. void b64dump (void const * memory, size_t extent, size_t column, FILE *fp)
  22. {
  23. byte * offset = (byte *)(memory);
  24. unsigned encode = 0;
  25. while (extent)
  26. {
  27. uint32_t word = 0;
  28. unsigned byte = 0;
  29. unsigned bits = BASE64_WORDSIZE - BASE64_BYTESIZE;
  30. while ((bits) && (extent))
  31. {
  32. bits -= BASE64_BYTESIZE;
  33. word |= *offset << bits;
  34. offset++;
  35. extent--;
  36. byte++;
  37. }
  38. if (byte++)
  39. {
  40. bits = BASE64_WORDSIZE - BASE64_BYTESIZE;
  41. while ((bits) && (byte))
  42. {
  43. bits -= BASE64_CHARSIZE;
  44. putc (BASE64_CHARSET [(word >> bits) & BASE64_CHARMASK], fp);
  45. byte--;
  46. encode++;
  47. }
  48. while (bits)
  49. {
  50. bits -= BASE64_CHARSIZE;
  51. putc ('=', fp);
  52. encode++;
  53. }
  54. if ((column) && !(encode%column))
  55. {
  56. putc ('\n', fp);
  57. }
  58. }
  59. }
  60. return;
  61. }
  62. #endif