c/c++语言开发共享hex到ascii字符串转换

我有一个hex字符串,并希望它在C中转换为ascii字符串。我怎么能完成这个?

    你需要同时取2(hex)字符…然后计算int值,然后使char转换像…

    char d = (char)intValue;

    为hex字符串中的每个2chars执行此操作

    如果字符串字符仅为0-9A-F,则此方法有效:

     #include  #include  int hex_to_int(char c){ int first = c / 16 - 3; int second = c % 16; int result = first*10 + second; if(result > 9) result--; return result; } int hex_to_ascii(char c, char d){ int high = hex_to_int(c) * 16; int low = hex_to_int(d); return high+low; } int main(){ const char* st = "48656C6C6F3B"; int length = strlen(st); int i; char buf = 0; for(i = 0; i < length; i++){ if(i % 2 != 0){ printf("%c", hex_to_ascii(buf, st[i])); }else{ buf = st[i]; } } } 

    很少像字母io这样的字符无法转换为相应的ASCII字符。 像字符串’6631653064316f30723161’对应fedora 。 但它给了fedra

    只需稍微修改hex_to_int()函数,它就适用于所有字符。 修改后的function是

     int hex_to_int(char c) { if (c >= 97) c = c - 32; int first = c / 16 - 3; int second = c % 16; int result = first * 10 + second; if (result > 9) result--; return result; } 

    现在尝试它将适用于所有角色。

    strtol()是你的朋友。 第三个参数是您要转换的数字基数。

    例:

    需要了解更多c/c++开发分享hex到ascii字符串转换,也可以关注C/ C++技术分享栏目---计算机技术网(www.ctvol.com)!

     #include  /* printf */ #include  /* strtol */ int main(int argc, char **argv) { long int num = 0; long int num2 =0; char * str. = "f00d"; char * str2 = "0xf00d"; num = strtol( str, 0, 16); //converts hexadecimal string to long. num2 = strtol( str2, 0, 0); //conversion depends on the string passed in, 0x... Is hex, 0... Is octal and everything else is decimal. printf( "%ldn", num); printf( "%ldn", num); } 

      以上就是c/c++开发分享hex到ascii字符串转换相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/980415.html

      (0)
      上一篇 2021年12月13日
      下一篇 2021年12月13日

      精彩推荐