Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read Specific Bytes Out of Byte Array C#

Tags:

arrays

c#

I am a newbie with a question regarding reading specific bytes out of an array in C#. I received an array response that is 128 bytes long and I am looking to read and store the first 4 bytes of the array. How do I do so?

I've read a number of posts about shifting bytes but was a bit confused and I am looking to get going in the right direction.

like image 459
Nevets Avatar asked Feb 10 '26 23:02

Nevets


2 Answers

Use one of the Array.Copy overloads:

byte[] bytes = new byte[4];

Array.Copy(originalArray, bytes, bytes.Length);
like image 190
dcastro Avatar answered Feb 13 '26 15:02

dcastro


Use Array.Copy method:

// your original array
var sourceArray = new byte[128];

// create a new one with the size you need
var firstBytes = new byte[4];

// copy the required number of bytes.
Array.Copy(sourceArray, 0, firstBytes, 0, firstBytes.Length);

If you do not need the rest of the data in the original array, you can also resize it, truncating everything after the first 4 bytes:

Array.Resize(ref sourceArray, 4);
like image 41
Knaģis Avatar answered Feb 13 '26 16:02

Knaģis