c#int整数をbyteバイト配列と16進数に変換

1123 ワード

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を16進数の文字列に変換します.
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;
        }