2009-08-14 135 views
1

你好,快速關於移位的問題移位N位

我有一個HEX = new byte [] {0x56,0xAF}的值;

其是0101 0110 1010 1111

我想第一n位,例如12

然後推卸其餘4(16-12),以獲得0000 0101 0110 1010(1386分解)

我無法用頭圍住它,並使其可擴展n位。

謝謝!

回答

1

你想要的東西像...

var HEX = new byte[] {0x56, 0xAF}; 
var bits = new BitArray(HEX); 
int bitstoShiftRight = 4; 
for (int i = 0; i < bits.Length; i++) 
{ 
    bits[i] = i < (bits.Length - bitstoShiftRight) ? bits[i + bitstoShiftRight] : false; 
} 
bits.CopyTo(HEX, 0); 
+0

謝謝,我喜歡這種方法,問題是BitArray的構造函數改變了每個字節的Endian的順序,當方法完成後,值出錯,id需要在實例化位數組之前反轉每個字節的位順序byes – Bobby 2009-08-14 16:06:09

0

如果你有全部K位,你想要的「第一」(如最顯著)n位,則您只需右鍵轉變時間。最後的k-n位將被刪除,通過結尾的「下降」,第一個n將移動到最不重要的一側。

+0

感謝您的迴應,問題是我真的不能移位一個字節數組,我需要單獨做它們,然後我失去了溢出,所以我的替代方案是將整個16位轉換爲int 16和shift在那個時候,沒有我想要的東西,因爲我現在需要知道長度,然後轉換爲 – Bobby 2009-08-14 16:03:34

0

用C狀符號應答,假定bits_in_byte是別處確定的比特的字節數:

int remove_bits_count= HEX.count*bits_in_byte - bits_to_keep; 
int remove_bits_in_byte_count= remove_bits_count % bits_in_byte; 

if (remove_bits_count > 0) 
{ 
    for (int iteration= 0; iteration<min(HEX.count, (bits_to_keep + bits_in_byte - 1)/bits_in_byte); ++iteration) 
    { 
     int write_index= HEX.count - iteration - 1; 
     int read_index_lo= write_index - remove_bits_count/bits_in_byte; 

     if (read_index_lo>=0) 
     { 
      int read_index_hi= read_index_lo - (remove_bits_count + bits_in_byte - 1)/bits_in_byte; 

      HEX[write_index]= 
       (HEX[read_index_lo] >> remove_bits_in_byte_count) | 
       (HEX[read_index_hi] << (bits_in_byte - remove_bits_in_byte_count)); 
     } 
     else 
     { 
      HEX[write_index]= 0; 
     } 
    } 
} 

假設你重寫原數組,則基本上採取每次寫入字節,並計算出它將從其獲得其移位的字節。你從數組的最後到最前面確保你永遠不會覆蓋你需要閱讀的數據。

6

早前我編碼這兩個功能,第一個移位位的字節[]指定的量的左側,第二做同樣向右:

左移:

public byte[] ShiftLeft(byte[] value, int bitcount) 
{ 
    byte[] temp = new byte[value.Length]; 
    if (bitcount >= 8) 
    { 
     Array.Copy(value, bitcount/8, temp, 0, temp.Length - (bitcount/8)); 
    } 
    else 
    { 
     Array.Copy(value, temp, temp.Length); 
    } 
    if (bitcount % 8 != 0) 
    { 
     for (int i = 0; i < temp.Length; i++) 
     { 
      temp[i] <<= bitcount % 8; 
      if (i < temp.Length - 1) 
      { 
       temp[i] |= (byte)(temp[i + 1] >> 8 - bitcount % 8); 
      } 
     } 
    } 
    return temp; 
} 

右移:

public byte[] ShiftRight(byte[] value, int bitcount) 
{ 
    byte[] temp = new byte[value.Length]; 
    if (bitcount >= 8) 
    { 
     Array.Copy(value, 0, temp, bitcount/8, temp.Length - (bitcount/8)); 
    } 
    else 
    { 
     Array.Copy(value, temp, temp.Length); 
    } 
    if (bitcount % 8 != 0) 
    { 
     for (int i = temp.Length - 1; i >= 0; i--) 
     { 
      temp[i] >>= bitcount % 8; 
      if (i > 0) 
      { 
       temp[i] |= (byte)(temp[i - 1] << 8 - bitcount % 8); 
      } 
     } 
    } 
    return temp; 
} 

如果您需要進一步的解釋,請對此進行評論,我會再編輯自己的帖子澄清...

+0

預先複製8位移位溢出不是一個壞主意。我看到這個想法之前,我的實現有2個嵌套for-s來處理溢出。 – vellotis 2012-11-13 13:07:43