2010-10-20 67 views
2

我在一個c#wpf應用程序中工作,其中我想做幾件事情。我正在使用字節數組來組成MIDI Show Control消息(在MSC規範1.0中指定)。轉換成字節數組並插入到其他數組中

該消息的結構是0x00字節就像消息所有部分之間的逗號。我撰寫類似這樣的消息:

byte[] data =   
             {(byte)0xF0, // SysEx 
             (byte)0x7F, // Realtime 
             (byte)0x7F, // Device id 
             (byte)0x02, // Constant 
             (byte)0x01, // Lighting format 
             (commandbyte), // GO   
             (qnumber), // qnumber  
             (byte)0x00, // comma 
             (qlist), // qlist 
             (byte)0x00, // comma 
             (byte)0xF7, // End of SysEx   


      }; 

我希望用戶填寫無符號整數(如215.5),我想(因爲當時消息被解釋錯不爲0x00個字節),這些數字轉換爲字節。

在上面提到的地方轉換數字並放置字節數組的最佳方法是什麼?

回答

1

發現了這件事是這樣的:

使用別人的轉換器這樣的代碼:

static byte[] VlqEncode(int value)  
{ 
    uint uvalue = (uint)value; 
    if (uvalue < 128) 
     return new byte[] { (byte)uvalue }; 

    // simplest case   
    // calculate length of buffer required 
    int len = 0;      
    do 
    {    
     uvalue >>= 7; 
    } while (uvalue != 0); 

    // encode   
    uvalue = (uint)value;   
    byte[] buffer = new byte[len]; 
    int offset = 0;   
    do {   buffer[offset] = (byte)(uvalue & 127); 
     // only the last 7 bits    
     uvalue >>= 7;   if(uvalue != 0) buffer[offset++] |= 128; 
     // continuation bit   
    } while (uvalue != 0);   
    return buffer;  
} 

然後我用這個來的整數轉換:

byte[] mybytearray = VlqEncode(integer); 

我再做出新我在其中按順序添加每個項目的列表列表:

ArrayList mymessage = new ArrayList(); 
foreach(byte uvalue in mymessage) 
{ 
    mymessage.Add((byte)uvalue); 
} 
mymessage.Add((byte)0x00); 

` 等等,直到我有正確的信息。然後我只需要將它轉換爲這樣的一個字節數組:

byte[] data = new byte[mymessage.count]; 
data = (byte[])mymessage.ToArray(typeof(byte));`