将具有数字的十六进制表示的字符串转换为实际的数字值 [英] Converting a string with a hexadecimal representation of a number to an actual numeric value
本文介绍了将具有数字的十六进制表示的字符串转换为实际的数字值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的字符串:
00c4
pre>
我需要将它转换为字面值表示的数值:
0x00c4
我该怎么办?
解决方案
strtol
函数(或strtoul
用于unsigned long),从stdlib.h C / C ++中的
允许在特定库中将字符串转换为长整型, p>中的
char * s =00c4;
char * e;
long int i = strtol(s,& e,16);
//检查* e =='\0',假设你的字符串应该只有
//包含十六进制数字。
//也检查errno == 0.
//如果你确定输入,你也可以使用NULL而不是& e。
I have a string like this:
"00c4"
And I need to convert it to the numeric value that would be expressed by the literal:
0x00c4
How would I do it?
解决方案The
strtol
function (orstrtoul
for unsigned long), fromstdlib.h
in C orcstdlib
in C++, allows you to convert a string to a long in a specific base, so something like this should do:char *s = "00c4"; char *e; long int i = strtol (s, &e, 16); // Check that *e == '\0' assuming your string should ONLY // contain hex digits. // Also check errno == 0. // You can also just use NULL instead of &e if you're sure of the input.
这篇关于将具有数字的十六进制表示的字符串转换为实际的数字值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文