byte array

G

Guest

simple question: i have a byte[] array.. how do i write to the console the
last 2 bytes of the byte[] array? thanks in advance
 
M

Morten Wennevik

Hi Rain,

You can just read the bytes using the index of the last two positions.
The last two positions can be calculated using Array.Length.



simple question: i have a byte[] array.. how do i write to the console
the
last 2 bytes of the byte[] array? thanks in advance
 
M

Marc Gravell

byte[] data = { 14, 242, 11, 34, 5 };
Console.WriteLine(data[data.Length - 2]);
Console.WriteLine(data[data.Length - 1]);

Or did you mean something more complex?

Marc
 
G

Guest

Hi Rain,

Use BitConverter.ToXXX methods. These methods take the byte[] array and the
start index. For instance to convert the last two bytes of a byte array to
Int16 you can write the following code.

byte[] data;

short i16 = ByteConverter.ToInt16(data,data.Length-3);

Hope this helps.
 
G

Guest

Hi Rain,

Ignore my previous code snippet. Read the code as below.

byte[] data;

short i16 = BitConverter.ToInt16(data,data.Length-3);

Hope this helps.


--
Regards,
Aditya.P


Adityanand Pasumarthi said:
Hi Rain,

Use BitConverter.ToXXX methods. These methods take the byte[] array and the
start index. For instance to convert the last two bytes of a byte array to
Int16 you can write the following code.

byte[] data;

short i16 = ByteConverter.ToInt16(data,data.Length-3);

Hope this helps.


--
Regards,
Aditya.P


Rain said:
simple question: i have a byte[] array.. how do i write to the console the
last 2 bytes of the byte[] array? thanks in advance
 
J

Jon Skeet [C# MVP]

Adityanand Pasumarthi said:
Ignore my previous code snippet. Read the code as below.

byte[] data;

short i16 = BitConverter.ToInt16(data,data.Length-3);

Hope this helps.

Not quite - you've got an off by one error. It should be:

short i16 = BitConverter.ToInt16(data,data.Length-2);

(So it'll use bytes with index data.Length-2 and data.Length-1.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top