tags:

views:

112

answers:

1

Hello, Now I have an array of 7 bits bytes or a string I want to take the last bit from the second byte and add it to the right most of the first and so on which will result in a new 8 bits byte Is there any direct way to do that than using loops and arrays? Example http://www.dreamfabric.com/sms/hello.html How can I do this by c#? Thanks.

+1  A: 

Here's a simple program that does what that page wants:

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();
    }
}

Example (same as on the page):

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"));
}

That outputs the required hex values (one on each line):

E8 32 9B FD 46 97 D9 EC 37
Daniel Earwicker