Two functions are provided to facilitate the conversion between the hexadecimal string and the ASCII string. When using the function, you must note that the returned strings are allocated through calloc on the stack. Therefore, remember to release the block after the return value is used, and the pointer to the block is null.
Char * chstohex (char * CHS) {char hex [16] = {'0', '1', '2', '3', '4', '5 ', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E ', 'F'}; int Len = strlen (CHS); char * ASCII = NULL; ASCII = (char *) calloc (LEN * 3 + 1, sizeof (char )); // calloc ASCII int I = 0; while (I <Len) {ASCII [I * 2] = hex [(INT) (char) CHS [I]/16)]; ASCII [I * 2 + 1] = hex [(INT) (char) chs [I] % 16)]; ++ I;} return ASCII; // ASCII Returns the unreleased string} // returns the hexadecimal string of the function input, and returns the corresponding string char * hextochs (char * ASCII) {int Len = strlen (ASCII ); if (LEN % 2! = 0) return NULL; char * CHS = NULL; CHS = (char *) calloc (LEN/2 + 1, sizeof (char )); // calloc CHS int I = 0; char ch [2] = {0}; while (I <Len) {ch [0] = (INT) ASCII [I]> 64 )? (ASCII [I] % 16 + 9): ASCII [I] % 16; ch [1] = (INT) ASCII [I + 1]> 64 )? (ASCII [I + 1] % 16 + 9): ASCII [I + 1] % 16; CHS [I/2] = (char) (CH [0] * 16 + CH [1]); I + = 2;} return CHS; // CHS is not released before return}
Hex and ASCII string Conversion