Skip to content

Instantly share code, notes, and snippets.

@githubutilities
Last active August 29, 2015 14:19
Show Gist options
  • Select an option

  • Save githubutilities/1d36dc73436afcca80ab to your computer and use it in GitHub Desktop.

Select an option

Save githubutilities/1d36dc73436afcca80ab to your computer and use it in GitHub Desktop.
C Tricks

C Tricks

Test the return type of sizeof operator

std::cout<<(typeid(sizeof(int))==typeid(std::size_t))<<std::endl;
void print_hexadecimal(unsigned char *ptr, size_t len) {
    for (size_t i = 0; i < len; i++)
        printf("%02x ", ptr[i]);
    putchar('\n');
}

// more generic one
// `in` is the pointer of the structure
// `len` is the byte length of the structure
void print_hexadecimal(const void *in, size_t len) {
    unsigned long long *ptr = (unsigned long long *)in;
    // convert length in one-byte data-type to length in long long
    size_t cell_len = sizeof(long long);
    len = (len + cell_len - 1) / cell_len;
    for (size_t i = 0; i < len; i++)
        printf("%016llx ", ptr[i]);
    putchar('\n');
}
// output in 32 byte length
void print_hexadecimal(const void *in, size_t len) {
    unsigned __INT32_TYPE__ *ptr = (unsigned __INT32_TYPE__ *)in;
    // convert length in one-byte data-type to length in long long
    size_t cell_len = sizeof(__INT32_TYPE__);
    len = (len + cell_len - 1) / cell_len;
    for (size_t i = 0; i < len; i++)
        printf("%08x ", ptr[i]);
    putchar('\n');
}
union foo {
  int a;   // can't use both a and b at once
  char b;
} foo;
union foo x;
x.a = 0xDEADBEEF;
x.b = 0x22;
printf("%x, %x\n", x.a, x.b);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment