c#十六进制转换十进制
展开全部
十六进制转十进制本身很简单:
如:
0102030AADAF
(16)
=
15*16^0+10*16^1+13*16^2+10*16^3+10*16^4+0*16^5+3*16^6+0*16^7+2*16^8+0*16^9+1*16^10+0*16^11
(10)
依据这个思路可以解决任何进制的互相转换问题,下面是代码:
C#代码:
using
System;
using
System.Collections.Generic;
using
System.Text;
namespace
HexStr2Dec
{
class
Program
{
static
void
Main(string[]
args)
{
string
hexStr
=
"0102030AADAF";
//
long
result
=
HexStr2Dec(hexStr);
Console.WriteLine(result.ToString());
Console.ReadKey();
}
///
<summary>
///
十六进制字符串转换为十进制数字
///
</summary>
///
<param
name="hexStr"></param>
///
<returns></returns>
private
static
long
HexStr2Dec(string
hexStr)
{
char[]
hexCharList
=
hexStr.ToCharArray();
long
result
=
0;
for
(int
i
=
0;
i
<
hexCharList.Length;
i++)
{
result
+=
HexChar2Dec(hexCharList[hexCharList.Length
-
1
-
i])
*
Power(16,
i);
}
return
result;
}
///
<summary>
///
十六进制字符转换为十进制数字
///
</summary>
private
static
long
HexChar2Dec(char
hexChar)
{
switch
(hexChar)
{
case
'0':
case
'1':
case
'2':
case
'3':
case
'4':
case
'5':
case
'6':
case
'7':
case
'8':
case
'9':
return
Convert.ToInt64(hexChar);
case
'A':
return
10;
case
'B':
return
11;
case
'C':
return
12;
case
'D':
return
13;
case
'E':
return
14;
case
'F':
return
15;
default:
throw
new
Exception("该字符不是十六进制字符");
}
}
///
<summary>
///
乘方x^y
///
</summary>
private
static
long
Power(int
x,
int
y)
{
long
result
=
1;
for
(int
i
=
0;
i
<
y;
i++)
{
result
*=
x;
}
return
result;
}
}
}
如:
0102030AADAF
(16)
=
15*16^0+10*16^1+13*16^2+10*16^3+10*16^4+0*16^5+3*16^6+0*16^7+2*16^8+0*16^9+1*16^10+0*16^11
(10)
依据这个思路可以解决任何进制的互相转换问题,下面是代码:
C#代码:
using
System;
using
System.Collections.Generic;
using
System.Text;
namespace
HexStr2Dec
{
class
Program
{
static
void
Main(string[]
args)
{
string
hexStr
=
"0102030AADAF";
//
long
result
=
HexStr2Dec(hexStr);
Console.WriteLine(result.ToString());
Console.ReadKey();
}
///
<summary>
///
十六进制字符串转换为十进制数字
///
</summary>
///
<param
name="hexStr"></param>
///
<returns></returns>
private
static
long
HexStr2Dec(string
hexStr)
{
char[]
hexCharList
=
hexStr.ToCharArray();
long
result
=
0;
for
(int
i
=
0;
i
<
hexCharList.Length;
i++)
{
result
+=
HexChar2Dec(hexCharList[hexCharList.Length
-
1
-
i])
*
Power(16,
i);
}
return
result;
}
///
<summary>
///
十六进制字符转换为十进制数字
///
</summary>
private
static
long
HexChar2Dec(char
hexChar)
{
switch
(hexChar)
{
case
'0':
case
'1':
case
'2':
case
'3':
case
'4':
case
'5':
case
'6':
case
'7':
case
'8':
case
'9':
return
Convert.ToInt64(hexChar);
case
'A':
return
10;
case
'B':
return
11;
case
'C':
return
12;
case
'D':
return
13;
case
'E':
return
14;
case
'F':
return
15;
default:
throw
new
Exception("该字符不是十六进制字符");
}
}
///
<summary>
///
乘方x^y
///
</summary>
private
static
long
Power(int
x,
int
y)
{
long
result
=
1;
for
(int
i
=
0;
i
<
y;
i++)
{
result
*=
x;
}
return
result;
}
}
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询