C# VB 实现10进制 16进制之间互相转换
程序员文章站
2023-12-09 23:38:21
方法1: 复制代码 代码如下: int d=10; d.tostring("x") //或把x改为x,,,就变成了16位的字符串了. int x=convert.toint...
方法1:
int d=10;
d.tostring("x") //或把x改为x,,,就变成了16位的字符串了.
int x=convert.toint32(d.tostring("x"),16);//把16进制的字符串变回10进制的.
方法2:
static void main()
{
int i = 446;
string hex = i.tostring( "x" /* or x * );
console.writeline( hex );
int j = hextoint( hex );
console.writeline( j );
}
static int hextoint(string hex)
{
hex = regex.replace(hex, "^0x", "", regexoptions.ignorecase);
if (regex.ismatch(hex, "[g-z]", regexoptions.ignorecase))
{
throw new exception("invalid hexadecimal expression.: 0x" + hex);
}
char[] chars = hex.toupper().tochararray();
array.reverse(chars);
int dec = 0;
for (int i = 0; i < chars.length; i++)
{
dec += hexmapping(chars[i]) * (int)math.pow(16, i);
}
return dec;
}
static int hexmapping(char c)
{
switch (c)
{
case '0':
return 0;
case '1':
return 1;
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
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("invalid hexadecimal character :" + c.tostring());
}
}
复制代码 代码如下:
int d=10;
d.tostring("x") //或把x改为x,,,就变成了16位的字符串了.
int x=convert.toint32(d.tostring("x"),16);//把16进制的字符串变回10进制的.
方法2:
复制代码 代码如下:
static void main()
{
int i = 446;
string hex = i.tostring( "x" /* or x * );
console.writeline( hex );
int j = hextoint( hex );
console.writeline( j );
}
static int hextoint(string hex)
{
hex = regex.replace(hex, "^0x", "", regexoptions.ignorecase);
if (regex.ismatch(hex, "[g-z]", regexoptions.ignorecase))
{
throw new exception("invalid hexadecimal expression.: 0x" + hex);
}
char[] chars = hex.toupper().tochararray();
array.reverse(chars);
int dec = 0;
for (int i = 0; i < chars.length; i++)
{
dec += hexmapping(chars[i]) * (int)math.pow(16, i);
}
return dec;
}
static int hexmapping(char c)
{
switch (c)
{
case '0':
return 0;
case '1':
return 1;
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
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("invalid hexadecimal character :" + c.tostring());
}
}