2009-09-29 56 views
0

現在我有一個7位字節的數組或字符串,我想從第二個字節中取出最後一位,並將它添加到第一個位置的最右邊,依此類推,這將導致新的8位字節是否有任何直接的方式來做到這一點比使用循環和數組? 示例http://www.dreamfabric.com/sms/hello.html 如何通過c#執行此操作? 謝謝。移位字節

回答

1

這裏有一個簡單的程序,這是否頁面想要的東西:

public class Septets 
{ 
    readonly List<byte> _bytes = new List<byte>(); 
    private int _currentBit, _currentByte; 

    void EnsureSize(int index) 
    { 
     while (_bytes.Count < index + 1) 
      _bytes.Add(0); 
    } 

    public void Add(bool bitVal) 
    { 
     EnsureSize(_currentByte); 

     if (bitVal) 
      _bytes[_currentByte] |= (byte)(1 << _currentBit); 

     _currentBit++; 
     if (_currentBit == 8) 
     { 
      _currentBit = 0; 
      _currentByte++; 
     } 
    } 

    public void AddSeptet(byte septet) 
    { 
     for (int n = 0; n < 7; n++) 
      Add(((septet & (1 << n)) != 0 ? true : false)); 
    } 

    public void AddSeptets(byte[] septets) 
    { 
     for (int n = 0; n < septets.Length; n++) 
      AddSeptet(septets[n]); 
    } 

    public byte[] ToByteArray() 
    { 
     return _bytes.ToArray(); 
    } 

    public static byte[] Pack(byte[] septets) 
    { 
     var packer = new Septets(); 
     packer.AddSeptets(septets); 
     return packer.ToByteArray(); 
    } 
} 

實例(如在頁面上相同):

static void Main(string[] args) 
{ 
    byte[] text = Encoding.ASCII.GetBytes("hellohello"); 

    byte[] output = Septets.Pack(text); 

    for (int n = 0; n < output.Length; n++) 
     Console.WriteLine(output[n].ToString("X")); 
} 

輸出所需的十六進制值(每行一個) :

E8 32 9B FD 46 97 D9 EC 37