uncategorized

C#數值轉換整理

常常需要撰寫對資料中的數值進行資料轉換來符合規格上的需求,如:10進位轉成16進位,10進位轉ASCII…等等。這邊把常用的一些數值轉換語法,像是10進位轉二進位,10進位轉16進位…等,在此做一下整理,避免臨時有需要使用時,卻一時無法想起怎樣使用。

10進位轉2進位


1
2
3
4
5
int d = 3;
//轉換資料
string str = Convert.ToString(d, 2);
//補足四碼
str = str.PadLeft(4,'0');

10進位轉16進位


1
2
3
int dint=11
//轉換16進位
string strHex= String.Format("{0:X}", dint);

16進位轉10進位


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
string s2="AB"
//轉換10進位
int j = 0;
int result = 0;
for (int i = 0; i < s2.Length; i++)
{
result = result * 16;
j = s2[i] - 48;
if (j < 10)
{
result = result + j;
}
else
{
result = result + j - 39;
}
}

或是

1
Convert.ToInt32("100", 16)

10進位轉ASCII


1
2
3
int t = 44;
//資料轉換
string s = Convert.ToString((char)t);

ASCII轉10進位


1
2
3
4
string str = ",";
//資料轉換
byte[] inputBytes =null;
inputBytes = Encoding.ASCII.GetBytes(str);

16進位轉ASCII


這邊做法與上述轉換相同,只是將兩道程序複合運作,先執行16進位轉10進位,再做10進位轉ASCII

ASCII轉16進位


這邊做法與上述轉換相同,只是將兩道程序複合運作,先執行10進位轉ASCII,再做10進位轉16進位