Last active
February 4, 2023 22:09
-
-
Save stigok/1737e05ef2c02cb03e7e584a8145b77e to your computer and use it in GitHub Desktop.
C program demonstrating byte array to hex string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> // printf, sprintf, fprintf | |
#include <stdlib.h> // malloc | |
int main() { | |
const unsigned char bytearr[] = { 0x12, 0x34, 0x56, 0x78 }; | |
const size_t arrlen = sizeof(bytearr); | |
const size_t hexlen = 2; // hex representation of byte with leading zero | |
const size_t outstrlen = arrlen * hexlen; | |
char * outstr = malloc(outstrlen + 1); | |
if (!outstr) { | |
fprintf(stderr, "Failed to allocate memory\n"); | |
return 1; | |
} | |
// Create a string containing a hex representation of `bytearr` | |
char * p = outstr; | |
for (size_t i = 0; i < arrlen; i++) { | |
p += sprintf(p, "%.2x", bytearr[i]); | |
} | |
printf("String variable contains:\n%s\n", outstr); | |
free(outstr); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment