Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add new byte in array and shift the rest of the bytes

Tags:

c#

I have an array look like this

17 8B 01 00 03 EA 05 00 14 0A 00 00 03 EA 05 00 14 0A 00 00 00 00 00 FF FF FF FF FF FF FF FF FF

I want to add an extra byte 0x00 after index 1 (8B) and move the rest of the bytes to right. The array is 32 byte long and after adding the extra byte (0x00) I want it to remain the same length as 32 bytes I dont care if I remove the FF at the end because its spare byte. So the new array should look like

17 8B 00 01 00 03 EA 05 00 14 0A 00 00 03 EA 05 00 14 0A 00 00 00 00 00 FF FF FF FF FF FF FF FF.

How can I do that in c#?

like image 955
Crazy Engineer Avatar asked Jul 27 '16 08:07

Crazy Engineer


2 Answers

If you use Array.Copy() then behind the scenes it will use a very efficient processor instruction to move the data:

byte[] array = { 0x17, 0x8B, 0x01, 0x00, 0x03, 0xEA, 0x05, 0x00, 0x14, 0x0A, 0x00, 0x00, 0x03, 0xEA, 0x05, 0x00, 0x14, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};

int positionToInsert = 2;
byte valueToInsert = 0;

Array.Copy(array, positionToInsert, array, positionToInsert+1, array.Length-positionToInsert-1);
array[positionToInsert] = valueToInsert;

Array.Copy() is implemented specifically to handle overlapping copies correctly.

like image 64
Matthew Watson Avatar answered Nov 14 '22 22:11

Matthew Watson


You could do something like:

public static void InsertByte(byte[] array, int index, byte value)
{
    // shifting all bytes one spot. (from back to front)
    for (int i = array.Length - 1; i > index; i--)
        array[i] = array[i - 1];

    // assigning the new value
    array[index] = value;
}

public static byte[] InsertByteInCopy(byte[] array, int index, byte value)
{
    byte[] copy = array.ToArray();
    InsertByte(copy, index, value);
    return copy;
}

Altering the current instance of the array is better for performance.


Using Array.Copy will do something like this: (untested)

public static void InsertByte2(byte[] array, int index, byte value)
{
    Array.Copy(array, index, array, index + 1, a.Length - index - 1);
    array[index] = value;
}
like image 22
Jeroen van Langen Avatar answered Nov 14 '22 22:11

Jeroen van Langen