2016-10-23 30 views
0

所以我有這個問題解決:編碼/解碼來自INT 14位到十六進制,並且反之亦然

寫一個小程序,包括對功能,可以

  1. 將整數轉換一個特殊的文本編碼,然後

  2. 將編碼值轉換回原來的整數。

的編碼功能

此功能需要在14位範圍以接受一個帶符號的整數[-8192 .. + 8191],並返回一個4個字符的字符串。

編碼過程如下:

  1. 添加到8192的原始值,因此它的範圍被轉換成[0..16383]

  2. 包該值裝入兩個字節,使得每個最顯著位被清零

未編碼中間值(作爲16位整數):

00HHHHHH HLLLLLLL 

編碼值:

0HHHHHHH 0LLLLLLL 
  • 格式的兩個字節作爲一個單一的4字符十六進制字符串並返回它。
  • 示例值:

    Unencoded (decimal) Encoded (hex) 
    
    0     4000 
    
    -8192    0000 
    
    8191     7F7F 
    
    2048     5000 
    
    -4096    2000 
    

    解碼功能

    你的解碼功能應該接受輸入的兩個字節,無論是在範圍[0x00..0x7F]和重新組合它們返回相應的整數[-8192 .. + 8191]


    這是m y 編碼函數工作,它會產生正確的結果。

    public static string encode(int num) 
        { 
         string result = ""; 
    
         int translated = num + 8192; 
    
         int lowSevenBits = translated & 0x007F; // 0000 0000 0111 1111 
    
         int highSevenBits = translated & 0x3F80; // 0011 1111 1000 0000 
    
         int composed = lowSevenBits + (highSevenBits << 1); 
    
         result = composed.ToString("X"); 
    
         return result; 
        } 
    

    我需要我的解碼功能的幫助,它目前沒有產生正確的結果,解碼功能需要每兩個十六進制字符串的0x00到0x7F的,將它們合併範圍,並返回解碼的整數。 在我的解碼函數中,我試圖將我在編碼函數中完成的操作反轉。

    public static short decode(string loByte, string hiByte) 
        { 
         byte lo = Convert.ToByte(loByte, 16); 
         byte hi = Convert.ToByte(hiByte, 16); 
    
         short composed = (short)(lo + (hi >> 1)); 
    
         short result = (short)(composed - 8192); 
    
         return result; 
        } 
    
    +1

    你已經說過,你需要解碼函數的幫助,但是你已經進入了很多不相關的細節,並沒有真正描述它的問題。 http://stackoverflow.com/help/mcve –

    +0

    @AdrianWragg謝謝,我更新了我的問題 –

    回答

    1

    解碼時,您嘗試將字節值(00-7F)右移。這會產生較小的值(00-3F)。相反,您應該將它左移7位,以產生更高的值(0000-3F80)。這個值然後可以與低位組合以產生期望的值。

    public static short decode(string loByte, string hiByte) 
    { 
        byte lo = Convert.ToByte(loByte, 16); 
        byte hi = Convert.ToByte(hiByte, 16); 
    
        short composed = (short)(lo + (hi << 7)); 
    
        short result = (short)(composed - 8192); 
    
        return result; 
    } 
    
    +0

    謝謝,這很有道理。 –

    相關問題