Hex and ASCII string Conversion

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.