[C language utility] Convert hex string to string represented by its corresponding hex values

Source: Internet
Author: User

/* For Example
* Hex string:
* Unsigned char * src = "0a0b0c0d"
* Converted string:
* Unsigned char * des = {0x0a, 0x0b, 0x0c, 0x0d}
* Reference:
* Http://bdn.borland.com/article/0,1410,17203,00.html
*/

# Include "stdafx. H"
# Include <iostream. h>
# Include <string. h>

Int axtoi (char * hexstg ){
Int n = 0; // position in string
Int m = 0; // position in digit [] to shift
Int count; // loop index
Int intvalue = 0; // integer value of hex string
Int digit [5]; // hold values to convert
While (n <4 ){
If (hexstg [N] = '/0 ')
Break;
If (hexstg [N]> 0x29 & hexstg [N] <0x40) // If 0 to 9
Digit [N] = hexstg [N] & 0x0f; // convert to int
Else if (hexstg [N]> = 'A' & hexstg [N] <= 'F') // If A to F
Digit [N] = (hexstg [N] & 0x0f) + 9; // convert to int
Else if (hexstg [N]> = 'A' & hexstg [N] <= 'F') // If A to F
Digit [N] = (hexstg [N] & 0x0f) + 9; // convert to int
Else break;
N ++;
}
Count = N;
M = n-1;
N = 0;
While (n <count ){
// Digit [N] is value of hex digit at position n
// (M <2) is the number of positions to shift
// Or the bits into Return Value
Intvalue = intvalue | (digit [N] <(M <2 ));
M --; // adjust the position to set
N ++; // next digit to process
}
Return (intvalue );
}

Void convert (char * SRC, long src_len, char * des, long * des_len)

{

Char tempstr [4] = {0 };

* Des_len = src_len> 2;

For (INT I = 0; I <(* des_len); I ++)

{

Strncpy (tempstr, SRC + I * 2, 2 );

Des [I] = (char) axtoi (tempstr );

}

}

Int main (){

Char SRC [20] = "01020304aa ";
 
Char supposed_des [10] = {0x01,0x02,0x03,0x04, 0xaa };

Char des [10] = {0 };
Long des_len = 0;

Convert (SRC, 10, Des, & des_len );

If (0 = memcmp (DES, supposed_des, des_len ))
Cout <"successful! "<Endl;
Else
Cout <"failed! /N "<Endl;

Return 0;
}

Related Article

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.