1.將數字轉換成byte[],高位在左,低位在右
使用時機: 將裝置Node ID,address 轉成byte[]
byte[] bai = BitConverter.GetBytes(Convert.ToInt32(textBox1.Text));
2.將Byte[]還原為數字
textBox2.Text = Convert.ToString(BitConverter.ToInt32(bai, 0));
3.將Hex字串轉成byte[]
private byte[] HexStrToBytes(string hexString)
{
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
return returnBytes;
}
4.將Byte[]資料寫到檔案(binary 檔案)
Stream fs = null;
BinaryWriter w = null;
byte[] ba = new byte[387];
fs = new FileStream(outFileName, FileMode.Create);
w = new BinaryWriter(fs);
Array.Clear(ba, 0, ba.Length);
ba = HexStrToBytes(dr["FP11"].ToString());
w.Write(ba);
w.Close();
fs = null;
w = null;
5. string類型轉成byte[]:
使用時機: 將姓名轉成byte[]
byte[] byteArray = Encoding.Default.GetBytes ( str );
6. byte[]轉成string:
string str = Encoding.Default.GetString ( byteArray );
7. string類型轉成ASCII byte[]:("01" 轉成 byte[] = new byte[]{ 0x30, 0x31})
使用時機: 將卡號轉成byte[]
byte[] byteArray = Encoding.ASCII.GetBytes ( str );
8. ASCII byte[] 轉成string:(byte[] = new byte[]{ 0x30, 0x31} 轉成 "01")
string str = Encoding.ASCII.GetString ( byteArray );
9. byte[] 轉成 Hex字串
使用時機: 將卡號,姓名轉成byte[],存檔備查
public static string ToHexString ( byte[] bytes ) // 0xae00cf => "AE00CF "
{
string hexString = string.Empty;
if ( bytes != null )
{
StringBuilder strB = new StringBuilder ();
for ( int i = 0; i < bytes.Length; i++ )
{
strB.Append ( bytes[i].ToString ( "X2" ) );
}
hexString = strB.ToString ();
}
return hexString;
}
10. 十進位轉成BCD
y = ((((y) / 10) << 4) | ((y) % 10));
11. BCD轉成十進位
x = (((((x) & 0xF0) >> 4) * 10) + ((x) & 0x0F));