将具有数字的十六进制表示的字符串转换为实际的数字值 [英] Converting a string with a hexadecimal representation of a number to an actual numeric value

查看:149
本文介绍了将具有数字的十六进制表示的字符串转换为实际的数字值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的字符串:

 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 (or strtoul for unsigned long), from stdlib.h in C or cstdlib 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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆