×
Namespaces

Variants
Actions

转换十六进制字符串为整数

From Nokia Developer Wiki
Jump to: navigation, search
Article Metadata

文章
Den123 在 10 Aug 2007 创建
最后由 hamishwillee 在 15 Dec 2011 编辑

最近做项目遇到了一个需要把十六进制字符串转换为整数的需求,没有在SDK中找到现成可以用的方法。于是自己实现了一个用于长度8位以内的十六进制字符串转为整数的方法,方法实现如下:

//十六进制字符串转为整数
// "1234" => 0x1234
static TInt HexString2Int(const TDesC & aHexStr)
{
TInt len = aHexStr.Length();
//防止溢出
if(len > 8) return 0;
TInt res = 0;
TInt tmp = 0;
const TUint16 * hexString = aHexStr.Ptr();
for (TInt i = 0; i < len; i++)
{
if( hexString[i]>= '0'&& hexString[i]<= '9' )
{
tmp = hexString[i]-'0';
} else if(hexString[i]>= 'a'&& hexString[i] <= 'f' )
{
tmp = hexString[i] -'a'+10;
}else if( hexString[i]>='A'&& hexString[i]<='F' )
{
tmp = hexString[i] - 'A' +10;
} else {
res = 0;
}
tmp <<= ((len-i-1)<<2);
res |= tmp;
}
return res;
}

使用示例

TInt res = StringUtil::HexString2Int(_L("Ef56"));

SDK提供的TLex类可以实现把16进制字符串转换成整数:

_LIT( KTestHexString, "Ef56" );
 
TLex lex( KTestHexString );
 
TUint num(0);
 
lex.Val( num, EHex );
 
另外TRadix还可以进行二进制,八进制的转换:
 
EBinary
Convert number into binary character representation.
 
 
EOctal
Convert number into octal character representation.
 
 
EDecimal
Convert number into decimal character representation.
 
 
EHex
Convert number into hexadecimal character representation
This page was last modified on 15 December 2011, at 13:21.
158 page views in the last 30 days.
×