2015-10-18 51 views
-4

您好,我需要扭轉這種代碼我會如何反轉? C#

public static byte[] CreateProtocolBuffer(params int[] values) 
    { 
     List<byte> ptr = new List<byte>(); 
     for (int x = 0; x < values.Length; x++) 
     { 
      int value = values[x]; 
      while (value > 0x7F) 
      { 
       ptr.Add((byte)((value & 0x7F) | 0x80)); 
       value >>= 7; 
      } 
      ptr.Add((byte)(value & 0x7F)); 

     } 
     return ptr.ToArray(); 
    } 

例如:

int ID = 1000005; 
byte[] ptr = CreateProtocolBuffer(ID); 

我需要使用ptr值來獲得1000005回來。

+2

歡迎來到Stack Overflow!請添加更多詳細信息,以澄清您提出的問題並提供必要的上下文。現在很難理解這裏的目標是什麼。 – brandaemon

+0

*總是*加回來,即使它不在那裏。這是不可逆的。 – Blindy

+1

@Bindind Huh?這是一個簡單的可變長度編碼,每個輸出字節使用7位數據。爲什麼它不可逆? – Corey

回答

1

您發佈的CreateProtocolBuffer方法中的代碼將每個整數值編碼爲一個字節流,其中每個字節包含7位數據和一個「繼續」標誌(位於高位)。根據所編碼的值,它可以產生1到5個字節的輸出。

要逆轉編碼,您需要讀取字節,直到找到高位清零的位,並將每個字節的7位組合在一起以獲取原始值。

這是你的代碼的簡單逆轉:

public static int[] FromProtocolBuffer(byte[] buffer) 
{ 
    List<int> result = new List<int>(); 
    short shift = 0; 
    int curr = 0; 
    foreach (byte b in buffer) 
    { 
     curr = curr | (((int)b & 0x7F) << shift); 
     if ((b & 0x80) == 0) 
     { 
      result.Add(curr); 
      curr = 0; 
      shift = 0; 
     } 
     else 
      shift += 7; 
    } 
    return result.ToArray(); 
} 

只是要小心,你不要嘗試這種方式編碼負值,否則將無法正常工作。更好地使整個事情工作在無符號整數。

+0

正常工作謝謝 – Khaled

1

請檢查一下,並考慮到建議的編碼模式不適用於負數(關於存儲在前導位中的符號信息丟失)。

public static int[] BackConversion(byte[] b) 
{ 
    var result = new List<int>(); 
    int current = 0; 
    int i_start = 0; 

    for (int i = 0; i < b.Length; i++) 
    { 
     current += (b[i] & 0x7F) << (i - i_start) * 7; 

     if ((b[i] & 0x80) == 0) 
     { 
      result.Add(current); 
      i_start = i + 1; 
      current = 0; 
     } 
    } 

    return result.ToArray(); 
} 

以下是如何使整個事物(編碼/解碼)與負數一起工作。用您的編碼代碼替換int value = values[x];uint value = (uint)values[x];

+0

'CreateProtocolBuffer'採用int數組。所以'BackConversion'也必須返回int數組。這隻適用於一個號碼。 –

+0

@ M.kazemAkhgary,我認爲其餘的可以對問題的作者進行練習。我已經更新了答案。 –