We sometimes need to print the string (or char array) with binary content in hexadecimal format, we then can use the following C function:
1 2 3 4 5 6 7 8 9 10 11 | void printCharInHexadecimal(const char* str, int len) { for (int i = 0; i < len; ++ i) { uint8_t val = str[i]; char tbl[] = "0123456789ABCDEF"; printf("0x"); printf("%c", tbl[val / 16]); printf("%c", tbl[val % 16]); printf(" "); } printf("\n"); } |
void printCharInHexadecimal(const char* str, int len) { for (int i = 0; i < len; ++ i) { uint8_t val = str[i]; char tbl[] = "0123456789ABCDEF"; printf("0x"); printf("%c", tbl[val / 16]); printf("%c", tbl[val % 16]); printf(" "); } printf("\n"); }
This C function requires two parameters: the char array (pointer) and the length to print. Then, it iterates over each byte, and convert the ASCII value to Hexadecimal value – and print it out in the form of “0x??” to the console.
–EOF (The Ultimate Computing & Technology Blog) —
GD Star Rating
loading...
167 wordsloading...
Last Post: Teaching Kids Programming - Recursive Depth First Search Algorithm to Compute the Max Average of a Binary SubTree
Next Post: Teaching Kids Programming - Recursive Depth First Search Algorithm to Count the Surrounded Islands