现在我有了一个7位字节的数组或一个字符串,我想从第二个字节中取出最后一位,并将其添加到第一个字节的最右边,依此类推,这将产生一个新的8位字节,除了使用循环和数组之外,还有什么直接的方法可以做到这一点吗?示例http://www.dreamfabric.com/sms/hello.html如何通过c#实现此目的?谢谢。
发布于 2009-09-29 13:54:53
下面是一个简单程序,它实现了该页面所需的功能:
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 https://stackoverflow.com/questions/1492435
复制相似问题