C语言 十六进制到 ascii 字符串转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5403103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hex to ascii string conversion
提问by nikhil
i have an hex string and want it to be converted to ascii string in C. How can i accomplish this??
我有一个十六进制字符串,并希望它在 C 中转换为 ascii 字符串。我怎样才能做到这一点??
回答by sharpner
you need to take 2 (hex) chars at the same time... then calculate the int value and after that make the char conversion like...
您需要同时获取 2 个(十六进制)字符...然后计算 int 值,然后进行字符转换,例如...
char d = (char)intValue;
char d = (char)intValue;
do this for every 2chars in the hex string
对十六进制字符串中的每 2 个字符执行此操作
this works if the string chars are only 0-9A-F:
如果字符串字符仅为 0-9A-F,则此方法有效:
#include <stdio.h>
#include <string.h>
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];
}
}
}
回答by summary
Few characters like alphabets i-o couldn't be converted into respective ASCII chars . like in string '6631653064316f30723161' corresponds to fedora. but it gives fedra
很少有像字母 io 这样的字符无法转换为相应的 ASCII 字符。就像字符串 '6631653064316f30723161' 对应于fedora。但它给了Fedra
Just modify hex_to_int() function a little and it will work for all characters. modified function is
只需稍微修改 hex_to_int() 函数,它将适用于所有字符。修改后的函数是
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;
}
Now try it will work for all characters.
现在尝试它适用于所有角色。
回答by Baldrickk
strtol()is your friend here. The third parameter is the numerical base that you are converting.
strtol()是你的朋友吗?第三个参数是您要转换的数字基数。
Example:
例子:
#include <stdio.h> /* printf */
#include <stdlib.h> /* 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( "%ld\n", num);
printf( "%ld\n", num);
}

