C语言 如何在C中将字符串转换为十六进制值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29547115/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 11:50:29  来源:igfitidea点击:

How to convert string to hex value in C

cstringhex

提问by Allamaprabhu

I have string "6A" how can I convert into hex value 6A?

我有字符串“6A”如何转换为十六进制值 6A?

Please help me with solution in C

请帮我解决C中的问题

I tried

我试过

char c[2]="6A"
char *p;
int x = atoi(c);//atoi is deprecated 

int y = strtod(c,&p);//Returns only first digit,rest it considers as string and
//returns 0 if first character is non digit char.

回答by Weather Vane

The question

问题

"How can I convert a string to a hex value?"

“如何将字符串转换为十六进制值?”

is often asked, but it's not quite the right question. Better would be

经常被问到,但这不是一个正确的问题。更好的是

"How can I convert a hex string to an integer value?"

“如何将十六进制字符串转换为整数值?”

The reason is, an integer (or char or long) value is stored in binary fashion in the computer.

原因是,整数(或 char 或 long)值以二进制方式存储在计算机中。

"6A" = 01101010

It is only in human representation (in a character string) that a value is expressed in one notation or another

只有在人类表示中(在字符串中),值才能以一种或另一种表示法表示

"01101010b"   binary
"0x6A"        hexadecimal
"106"         decimal
"'j'"         character

all represent the same value in different ways.

都以不同的方式表示相同的值。

But in answer to the question, how to convert a hex string to an int

但是在回答这个问题时,如何将十六进制字符串转换为 int

char hex[] = "6A";                          // here is the hex string
int num = (int)strtol(hex, NULL, 16);       // number base 16
printf("%c\n", num);                        // print it as a char
printf("%d\n", num);                        // print it as decimal
printf("%X\n", num);                        // print it back as hex

Output:

输出:

j
106
6A