Convert the MFC hexadecimal string "0x *****" to a decimal number.

Source: Internet
Author: User

In programs, we sometimes need to convert a hexadecimal string to a decimal number. For example:
Char * PTR = "0x11 ";
Int n = 0;
// We want n to be equal to 0x11, that is, 17

In C, we usually use the following method to convert a string to an integer:

[CPP]
View plaincopyprint?
  1. Char * PTR = "123 ";
  2. Int n = 0;
  3. N = atoi (PTR );
  4. Printf ("% d/N", N );
  5. // Output: 123

Char * PTR = "123"; <br/> int n = 0; <br/> N = atoi (PTR ); <br/> printf ("% d/N", n); <br/> // output: 123

However, the atoi library function can only convert a decimal string to an int integer. For example:

[CPP]
View plaincopyprint?
  1. # Include <stdlib. h>
  2. # Include <stdio. h> // atoi header file
  3. Int main (void)
  4. {
  5. Int N;
  6. Char * STR = "12345.67 ";
  7. N = atoi (STR); // int atoi (const char * nptr );
  8. Printf ("string = % s integer = % d/N", STR, N );
  9. Return 0;
  10. }
  11. /* Output:
  12. String = 12345.67 integer = 12345
  13. */

# Include <stdlib. h> <br/> # include <stdio. h> // atoi header file <br/> int main (void) <br/>{< br/> int N; <br/> char * STR = "12345.67 "; <br/> N = atoi (STR); // int atoi (const char * nptr ); <br/> printf ("string = % s integer = % d/N", STR, n); <br/> return 0; <br/>}< br/>/* output: <br/> string = 12345.67 integer = 12345 <br/> */

Therefore, it is impossible to convert "0x11" to a decimal integer 17 using the atoi function. If used, the following results are output:

[CPP]
View plaincopyprint?
  1. Int N;
  2. Char * STR = "0x11 ";
  3. N = atoi (STR); // the return value n is equal to 0 (apparently not the expected result)

Int N; <br/> char * STR = "0x11"; <br/> N = atoi (STR ); // return value n is equal to 0 (obviously not the expected result) <br/>

What should we do? At this time, someone will think, it's easy to do. We can write a function to convert it, for example, using the following method:
Note: We have created a Win32 console program with VC 6.0. For convenience, the program uses the cstring type variable and requires some modifications.
(1) include the afx. h header file
(2) in project-> Settings-> General-> Mircosoft foundation classes, select use MFC in a shared DLL
Then we can use the cstring variable in the Win32 console. Otherwise, a compilation error occurs.

[CPP]
View plaincopyprint?
  1. # Include <iostream>
  2. # Include <afx. h>
  3. Int changenum (cstring STR, int length)
  4. {
  5. Char revstr [16] = {0 };
    // According to the length of the hexadecimal string, note that the array should not cross the border.
  6. Int num [16] = {0 };
  7. Int COUNT = 1;
  8. Int result = 0;
  9. Strcpy (revstr, STR );
  10. For (INT I = length-1; I> = 0; I --)
  11. {
  12. If (revstr [I]> = '0') & (revstr [I] <= '9 '))
  13. Num [I] = revstr [I]-48; // the ASCII value of character 0 is 48
  14. Else if (revstr [I]> = 'A') & (revstr [I] <= 'F '))
  15. Num [I] = revstr [I]-'A' + 10;
  16. Else if (revstr [I]> = 'A') & (revstr [I] <= 'F '))
  17. Num [I] = revstr [I]-'A' + 10;
  18. Else
  19. Num [I] = 0;
  20. Result = Result + num [I] * count;
  21. Count = count * 16; // hexadecimal (if it is octal, multiply it here by 8)
  22. }
  23. Return result;
  24. }
  25. Int main ()
  26. {
  27. Cstring STR = "0x11 ";
  28. Int n = 0;
  29. N = changenum (STR, str. getlength ());
  30. Printf ("% d/N", N );
  31. Return 0;
  32. }
  33. /* Output:
  34. 17
  35. */

# Include <iostream> <br/> # include <afx. h> <br/> int changenum (cstring STR, int length) <br/>{< br/> char revstr [16] = {0 }; // according to the length of the hexadecimal string, note that the array should not be out of bounds <br/> int num [16] = {0}; <br/> int COUNT = 1; <br/> int result = 0; <br/> strcpy (revstr, STR); <br/> for (INT I = length-1; I >= 0; I --) <br/>{< br/> If (revstr [I]> = '0') & (revstr [I] <= '9 ')) <br/> num [I] = revstr [I]-48; // The ASCII value of 0 is 48 <br/> else if (revstr [I]> = 'A ') & (revstr [I] <= 'F') <br/> num [I] = revstr [I]-'A' + 10; <br/> else if (revstr [I]> = 'A') & (revstr [I] <= 'F ')) <br/> num [I] = revstr [I]-'A' + 10; <br/> else <br/> num [I] = 0; <br/> result = Result + num [I] * count; <br/> COUNT = count * 16; // hexadecimal (if it is octal, multiply it here by 8) <br/>}< br/> return result; <br/>}< br/> int main () <br/>{< br/> cstring STR = "0x11"; <br/> int n = 0; <br/> N = changenum (STR, str. getlength (); <br/> printf ("% d/N", n); <br/> return 0; <br/>}< br/>/* output: <br/> 17 <br/> */

Yes, the above method can get the value we want. Is there a simpler way? Of course!

Method 1:

[CPP]
View plaincopyprint?
  1. # Include <stdio. h>
  2. Int main ()
  3. {
  4. Char szvalue [] = "0x11 ";
  5. Int nvalude = 0;
  6. Sscanf (szvalue, "% x", & nvalude );
  7. Printf ("% d/N", nvalude );
  8. Return 0;
  9. }
  10. /* Output:
  11. 17
  12. */

# Include <stdio. h> <br/> int main () <br/>{< br/> char szvalue [] = "0x11"; <br/> int nvalude = 0; <br/> sscanf (szvalue, "% x", & nvalude); <br/> printf ("% d/N", nvalude); <br/> return 0; <br/>}< br/>/* output: <br/> 17 <br/> */

The library function sscanf is mainly used:
Function Name: sscanf
Function: format the input from the string.
Usage: int sscanf (char * string, char * Format [, argument,...]); // % x is the type we want to format, that is, the output hexadecimal

Method 2:

[CPP]
View plaincopyprint?
  1. # Include <stdio. h>
  2. # Include <stdlib. h> // strtol header file
  3. Int main ()
  4. {
  5. Char * P = "0x11 ";
  6. Char * STR;
  7. Int I = (INT) strtol (p, & STR, 16); // hexadecimal
  8. Printf ("% d/N", I );
  9. Return 0;
  10. }
  11. /* Output:
  12. 17
  13. */

# Include <stdio. h> <br/> # include <stdlib. h> // strtol header file <br/> int main () <br/> {<br/> char * P = "0x11 "; <br/> char * STR; <br/> int I = (INT) strtol (p, & STR, 16 ); // hexadecimal <br/> printf ("% d/N", I); <br/> return 0; <br/>}< br/>/* output: <br/> 17 <br/> */

The strtol library function is mainly used in the following ways:

Function Name: strtol
Function: converts a string to a long integer.
Usage: Long strtol (char * STR, char ** endptr, int base); // base indicates the number of hexadecimal numbers to be converted.
Program example:

[CPP]
View plaincopyprint?
  1. # Include <stdlib. h>
  2. # Include <stdio. h>
  3. Int main (void)
  4. {
  5. Char * string =
    "0x11", * endptr;
  6. Long lnumber;
  7. /* Strtol converts string to long integer */
  8. Lnumber = strtol (string, & endptr, 16 );
  9. Printf ("string = % s long = % LD/N", String, lnumber );
  10. Return 0;
  11. }
  12. /* Output:
  13. String = 0x11 long = 17
  14. */

# Include <stdlib. h> <br/> # include <stdio. h> <br/> int main (void) <br/>{< br/> char * string = "0x11", * endptr; <br/> long lnumber; <br/>/* strtol converts string to long integer */<br/> lnumber = strtol (string, & endptr, 16 ); <br/> printf ("string = % s long = % LD/N", String, lnumber); <br/> return 0; <br/>}< br/>/* output: <br/> string = 0x11 long = 17 <br/> */

In the MFC program of VC 6.0, we can use the strtol function to convert the handle sometimes, for example:

[CPP]
View plaincopyprint?
  1. Handle handle = (handle) strtol (STR, null, 16 );

Handle handle = (handle) strtol (STR, null, 16 );

PS: What is a handle?

A handle is a 32-bit integer that uniquely identifies a variety of memory objects.
Some are unique in the system (such as window handle), and some are unique in the current process or thread (such as thread handle, with another identifier globally ).

The details can be divided into many types, all starting with H. Use long in VB.
Common include Windows handle (hwnd), device description table handle (HDC), memory handle (hmem), file handle, Process Handle, thread handle, and pen type handle (Hpen ), font handle (hfont), area handle (hrgn), and so on.

When applying for a handle, resources are occupied, which can be divided into three types: system, user, and GDI. Windows resources are fixed and do not expand as the memory expands. Therefore, you must release the resources after use.


Method 3:

On the Internet, I also saw a friend put forward a method to read and write INI files (I think this method is too inefficient, after all, to read and write files) and extract it as follows:

[CPP]
View plaincopyprint?
  1. // Store handle
  2. Struct tag_struct
  3. {
  4. Hwnd;
  5. };
  6. Struct tag_struct struct;
  7. Struct. hwnd = m_hwnd;
  8. // Write the struct containing the handle to the INI File
  9. Writeprivateprofilestruct ("section", "key", & struct, sizeof (struct), "C: // 1.ini ");
  10. // Read handle
  11. Struct tag_struct
  12. {
  13. Hwnd;
  14. };
  15. Struct tag_struct struct;
  16. // Read handle from the INI file containing the handle struct
  17. Getprivateprofilestruct ("section", "key", & struct, sizeof (struct), "C: // 1.ini ");

// Store handle <br/> struct tag_struct <br/>{< br/> hwnd; <br/>}; <br/> struct tag_struct struct; <br/> struct. hwnd = m_hwnd; <br/> // write the struct containing the handle to the INI file <br/> writeprivateprofilestruct ("section", "key", & struct, sizeof (struct ), "C: // 1.ini"); <br/> // read handle <br/> struct tag_struct <br/>{< br/> hwnd; <br/> }; <br/> struct tag_struct struct; <br/> // read handle from the INI file containing the handle struct <br/> getprivateprofilestruct ("section", "key", & struct, sizeof (struct), "C: // 1.ini ");


The above is a method that I know to convert a hexadecimal string into an integer value. There may be more appropriate methods. Please help me add a comment when I see this article, thank you!


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.