Main Site Documentation

How to access nth element in byte array?


I have a data packet from a modem that contains a zero terminated phone number and then the message after this, also zero byte terminated.

How can I get a pointer to the second part of the array after working out where the zero terminator on the phone number was?

        // Get the phone number who sent us the SMS
        XbeeMessage = new string(Encoding.UTF8.GetChars(response.Value));
        // We need to find the null in the bytes and then extract the message
        // from this
        int index = 0;
        while(response.Value[index] != 0)
        index++;        // Jump past the zero 

        XbeeMessage = new string(Encoding.UTF8.GetChars(response.Value[index]));

The last line here gives an error of course. So how to do this?


I usually use a queue object, and then peek and pop until I get to the byte I need to find.


I guess

        byte[] _responseValues = new byte[30]; //find the zero byte
        byte[] _messageA = Encoding.UTF8.GetBytes("Testing");
        Array.Copy(_messageA, _responseValues, _messageA.Length);
        byte[] _messageB = Encoding.UTF8.GetBytes("One two three");
        Array.Copy(_messageB, 0, _responseValues, _messageA.Length + 1, _messageB.Length);

        int _indexer = 0;

        while (_indexer < _responseValues.Length && _responseValues[_indexer] != 0) {
        _indexer++;//jump past the zero
        string _value = new string(Encoding.UTF8.GetChars(_responseValues, _indexer, _responseValues.Length - _indexer));


IndexOf and SubString methods?


Not tested : yourString.Split('\0'); ? It should give you an array of two strings, the second one being the message.


It’s not a string, it’s a byte array.

    byte[] number = new byte[]{0x31,0x32, 0x33, 0x34, 0x35, 0x30, 0x41, 0x42,0x43};
    int index = Array.IndexOf(number, 0x30) + 1;
    int length = number.Length - index;
    byte[] chopped = new byte[length];
    Array.Copy(number, index, chopped, 0, length);
    string str = new string(Encoding.UTF8.GetChars(chopped));