2010-09-19 71 views
0

我想要的int值轉換爲byte array,但我使用了byte的MIDI信息(表示爲0x00 byte這是使用GetBytes作爲分隔符時返回)這使得我的MIDI信息無用。如何將int轉換爲沒有0x00字節的字節數組?

我想將int轉換爲array,它留下0x00字節並且只包含包含實際值的字節。我怎樣才能做到這一點?

+1

哪端?大還是小?示例輸入/輸出將確實幫助我們確定您的意圖。通過編碼,具體問題很重要。 – 2010-09-19 15:45:43

+0

我的意思是,當我將int 1轉換爲一個字節數組時,我不想要0x01 0x00 0x00 0x00但只是0x01 – internetmw 2010-09-19 16:01:23

+0

這個問題的描述措辭可怕。您正在使用的系統沒有附帶任何文檔,或者您是逆向工程? – 2010-09-19 16:13:22

回答

0

根據本補充說,這應該做你需要什麼信息:

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 { 
      len++; 
      uvalue >>= 7; 
     } while (uvalue != 0); 
     // encode (this is untested, following the VQL/Midi/protobuf confusion) 
     uvalue = (uint)value; 
     byte[] buffer = new byte[len]; 
     for (int offset = len - 1; offset >= 0; offset--) 
     { 
      buffer[offset] = (byte)(128 | (uvalue & 127)); // only the last 7 bits 
      uvalue >>= 7; 
     } 
     buffer[len - 1] &= 127; 
     return buffer; 
    } 
+0

也許維基百科的錯誤與protobuf使用的編碼相同,但這是LSB優先和VLQ優先優先。 – 2010-09-19 19:11:07

+0

@Ben - 我可以確認protobuf總是LSB優先[來源](http://code.google.com/apis/protocolbuffers/docs/encoding.html) - 所以維基百科可能是錯的;引用:「除了最後一個字節,varint中的每個字節都有最高有效位(msb) - 這表示還有更多字節出現,每個字節的低7位用於存儲二進制補碼錶示以7位組爲單位,**最不重要的組第一**。「 – 2010-09-19 19:48:51

+0

當然,除了最後一組的MSB,只需倒轉數組就可以解決這個問題... – 2010-09-19 19:51:06

1

你完全誤解了你所需要的,但幸運的是你提到了MIDI。您需要使用MIDI定義的多字節編碼,這與UTF-8有點類似,因爲少於8位的數據被放入每個八位位組,其餘的提供有關使用的位數的信息。

請參閱the description on wikipedia。密切關注protobuf使用這種編碼的事實,你可能會重用一些Google的代碼。

+0

UTF8與protobuf使用的編碼(和Midi似乎)完全不同 - 但是,是的,protobuf代碼應該很好地工作。 – 2010-09-19 18:02:45