0

I want to transmit one APDU and I get back the response. I want to check the last two bytes by an API which will log the comparison.

byte[] response = Transmit(apdu);

//response here comes will be 0x00 0x01 0x02 0x03 0x04 
//response.Length will be 5


byte[] expectedResponse = { 0x03, 0x04 };

int index = (response.Length)-2;

Log.CheckLastTwoBytes(response[index],expectedResponse);

//The declaration of CheckLastTwoBytes is 
//public static void CheckLastTwoBytes(byte[] Response, byte[] ExpResp)

This is an error of invalid arguments. How can I pass the last 2 bytes to APIs?

3
  • Actually I wanted to know, if it is possible to pass substring using index without using temporary array. (like how we can do in C) Commented Nov 29, 2012 at 3:31
  • 1
    Not in C#, sorry to say. Commented Nov 29, 2012 at 4:12
  • 1
    ArraySegment is a way to reference a slice of an array without making a copy of it Commented Nov 29, 2012 at 4:18

5 Answers 5

3

Use Array.Copy

byte[] newArray = new byte[2];
Array.Copy(response, response.Length-2, newArray, 2);
Log.CheckLastTwoBytes(newArray,expectedResponse);
Sign up to request clarification or add additional context in comments.

2 Comments

Or... you could just have two assignments? It's just two bytes. No need for actually Array.Copy...
yeah, Array.Copy can be replaced with 2 assignments.
1
new ArraySegment<byte>(response, response.Length - 2, 2).Array

EDIT: nevermind this, apparently .Array just returns the original entire array and not the slice. You would have to modify your other method to accept ArraySegment instead of byte[]

Comments

1

Since the type of response[index] is byte (not byte[]), it's not surprising that you'd get that error.

If Log.CheckLastTwoBytes really does check just the last two bytes of its Response parameter, then you should just pass response:

   Log.CheckLastTwoBytes(response, expectedResponse)

Comments

1

You can't have a subarray just like that, no...

First solution, obvious one:

var tmp = new byte[] { response[response.Length - 2],
                       response[response.Length - 1] };

Log.CheckLastTwoBytes(tmp, expectedResponse);

Or, you could do this:

response[0] = response[response.Length - 2];
response[1] = response[response.Length - 1];

Log.CheckLastTwoBytes(response, expectedResponse);

It might be that this function doesn't check for exact lengths, etc, so you could just put the last two bytes as the first two, if you don't care about destroying the data.

Comments

0

Or, alternatively, you can use linq:

byte[] lastTwoBytes = response.Skip(response.Length-2).Take(2).ToArray();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.