1.将int转换为字节数组:
private byte[] ConvertHex(int vel)
{
int velocity = vel;
byte[] hex = new byte[4];
hex[0] = (byte)(velocity & 0xff);
hex[1] = (byte)((velocity >> 8) & 0xff); //先右移再与操作
hex[2] = (byte)((velocity >> 16) & 0xff);
hex[3] = (byte)((velocity >> 24) & 0xff);
return hex;
}
2.将int转换为十六进制的字符串:
private StringBuilder ConvertHex1(int vel)
{
int velocity = vel;
byte[] hex = new byte[4];
hex[0] = (byte)(velocity & 0xff);
hex[1] = (byte)((velocity >> 8) & 0xff);
hex[2] = (byte)((velocity >> 16) & 0xff);
hex[3] = (byte)((velocity >> 24) & 0xff);
StringBuilder tmp = new StringBuilder();
for (int i = 0; i < hex.Length - 1; i++)
{
tmp.Append(hex[i].ToString("x2")); //转为16进制,当只有一个字符时补0
}
return tmp;
}