private void btn1_Click(object sender, EventArgs e) { int value = 10; textBox2.Text = Convert.ToString(value, 16); }
●值(Value)轉16進位字串(string) - 在前面補0
private void btn1_Click(object sender, EventArgs e) { int value = 10; textBox2.Text = value.ToString("X2"); }
private void btn1_Click(object sender, EventArgs e) { int value = 10; textBox2.Text = String.Format("0x{0:X2}", value); }
補充說明:多個value用法及不同格式
textBox2.Text
= String.Format("0x{0:X2}, 0x{1:X2},
0x{2:0.00%}",
value0, value1, (float)value1/value2);
X: 格式,十六進位
D: 格式,十進位
E: 科學記號
N: 用分號隔開
D: 格式,十進位
E: 科學記號
N: 用分號隔開
2: 顯示兩位數寬度,若不足,會補0
●byte陣列轉成字串
private void btn1_Click(object sender, EventArgs e) { byte[] bBuff = {0x41, 0x42, 0x43, 0x44}; //範例是轉換0x42,0x43 textBox2.Text = Encoding.ASCII.GetString(bBuff, 2, 2); }
●16進位字串(String)轉成值(Value)
private void btn1_Click(object sender, EventArgs e) { int value; string String = "0A"; /*Convert string to value*/ value = Convert.ToByte(String, 16); /*Display value converted to string*/ textBox2.Text = Convert.ToString(value); }
●16進位字串(Hex string)轉成位元組陣列Byte[]
string hexString = richTextBox1.Text; byte[] data = new byte[hexString.Length / 2]; for (int i = 0; i < data.Length; i++) { string byteValue = hexString.Substring(i * 2, 2); /*Check input data*/ data[i] = byte.Parse(byteValue, NumberStyles.HexNumber); }
byte b; s = "1"; b = Convert.ToByte(s); // b = 0x01;
C# String.Format用法和格式说明
沒有留言:
張貼留言