简体   繁体   English

在不使用库函数的情况下将 C 中的 ASCII 数字转换为十六进制数字

[英]Converting an ASCII number to a Hex number in C without using library functions

I want to convert an 32-bit ASCII number (eg "FE257469") to the equivalent 32-bit hex number which will be stored on a 32-bit variable.我想将 32 位 ASCII 数字(例如“FE257469”)转换为等效的 32 位十六进制数字,该数字将存储在 32 位变量中。 Most importnatly, I want to do that without using any library function like sscanf(), atoi(), etc.最重要的是,我想在使用任何库 function (如 sscanf()、atoi() 等)的情况下做到这一点。

Any ideas on that?有什么想法吗?

Thank in advance.预先感谢。

The usual way is something like:通常的方式是这样的:

initialize result to 0将结果初始化为 0

  1. convert one digit of input to decimal to get current digit将输入的一位数字转换为十进制以获取当前数字
  2. multiply result by 16结果乘以 16
  3. add current digit to result将当前数字添加到结果
  4. repeat steps 1-3 for remaining digits对剩余的数字重复步骤 1-3

Here is an implementation of such a function based on a switch:这是一个基于开关的 function 的实现:

unsigned int parseHex( char *str )
{
    unsigned int value = 0;

    for(;; ++str ) switch( *str )
    {
        case '0': case '1': case '2': case '3': case '4':
        case '5': case '6': case '7': case '8': case '9':
            value = value << 4 | *str & 0xf;
            break;
        case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
        case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
            value = value << 4 | 9 + *str & 0xf;
            break;
        default:
            return value;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM