Skip to content

Instantly share code, notes, and snippets.

@ljrk0
Created August 27, 2016 14:14
Show Gist options
  • Save ljrk0/dc08ad0ad2dd235c4a20f7a686ee2f14 to your computer and use it in GitHub Desktop.
Save ljrk0/dc08ad0ad2dd235c4a20f7a686ee2f14 to your computer and use it in GitHub Desktop.
c small utility functions
#include <stdint.h>
#include <inttypes.h>
#include <stdlib.h>
#include <stdio.h>
/*
* generic array print function.
*
* prints array p with len elements of each width size.
* needs provided function f which should return a string representation of an
* element if called with a maximum size for the provided buffer and the
* buffer to write to itself.
*/
void parray(void *p, uint8_t width, size_t len, char *f(void *, size_t, char *))
{
char buf[10];
for (size_t i = 0; i < len; i++)
{
printf("%c%s%c",
(i==0) ? '[' : ' ',
f((p+(i*width)), 10, buf),
(i+1 >= len) ? ']' : ',');
}
printf("\n");
}
char *pr_uint32_t(void *x, size_t n, char buf[n])
{
snprintf(buf, n, "%" PRIu32, *(uint32_t *)(x));
return buf;
}
int main()
{
uint32_t data[] = { 2, 4, 1, 9, 0, 32 };
parray(data, sizeof data[0], sizeof data / sizeof data[0], pr_uint32_t);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment