C#中的数据转换


private void testConvert()
{
string a = "1110101010010010111110";
label1.Text = bin2hex(a).ToString();//2进制转16进制 3AA4BE

string b = "7D3C";
label2.Text = hex2bin(b).ToString();//16进制转2进制 0111110100111100

int c =198;
label3.Text = c.ToString("X4");//10进制转16进制,并用0补齐到4位 00C6

string d = "AB0C";
label4.Text = Convert.ToInt32(d, 16).ToString();//16进制转10进制(int32) 43788
//Convert.ToByte(d,16)//16进制转10进制(byte)要注意大小
}
private StringBuilder hex2bin(string sHex)
{
StringBuilder sbBin = new StringBuilder();
foreach (char c in sHex)
{
int a = Convert.ToInt32(c.ToString(), 16);//16进制转10进制
sbBin.Append(Convert.ToString(a, 2).PadLeft(4,'0'));//10进制转2进制并在前面补0到补齐4位
}
return sbBin;
}
private StringBuilder bin2hex(string sBin)
{
int count=0;
StringBuilder sbHex=new StringBuilder();
count=sBin.Length / 4;
//先判断长度,不足4的倍数的时候前面补0
if (sBin.Length % 4 != 0) sBin = sBin.PadLeft( ++count * 4, '0');
for (int i = 0; i < count; i++)
{
int a = Convert.ToInt32(sBin.Substring(i*4,4),2);//2进制转10进制
sbHex.Append(a.ToString("X"));//10进制转16进制
}
return sbHex;
}

你可能感兴趣的:(C#)