從 Decimal 直接轉換為 Bytes.
// using System.Collections.Generic; int _num = 2550; List<byte> _list = new List<byte>(); while( _num > 0 ) { // do while number more then 0 _list.Add( (byte)(_num & 0x00ff) ); // Byte mask : number > 255 will ignore. _num >>= 8; // move 8 digit right in binary } _list.Reverse(); // we calculate form EOL, remember? reverse it. return _list.ToArray(); // output as Byte array 09,F6
從 Hexadecimal 轉換為 Bytes
public static byte[] ToByte(string _hexString, int _digit=2) { // make sure the _hexString's length is matching the byte format, group by 2 int _no = (Mathf.FloorToInt(_hexString.Length/_digit)*_digit) + ((_hexString.Length%_digit)*_digit); _hexString = _hexString.PadLeft(_no,'0'); byte[] _bytes = new byte[_hexString.Length/_digit]; for (int i = 0; i < _bytes.Length; i++) { // only taken target hex number range string _hexByte = _hexString.Substring(i * _digit, _digit); // Convert "_hexByte" to bytes. _bytes[i] = byte.Parse(_hexByte, System.Globalization.NumberStyles.HexNumber); } return _bytes; }