0

I have a byte Array that contains the char '%' (25 hex, 37 decimal). I would like to get the index of this byte, however, none of these methods work, and -1 is returned. How to get the index of a specific byte in a byte array?

int byteIndex = Array.IndexOf(bytesDataArray, '%');
int byteIndex = Array.IndexOf(bytesDataArray, 37);
int byteIndex = Array.IndexOf(bytesDataArray, 0x25);
5
  • 1
    Bytes and chars are different types. What is actually in the byte array? Commented May 17, 2021 at 10:28
  • 2
    Array.IndexOf has overloads which take object, and so you need to make sure that the data type of the thing you're searching for is correct. You've got an array of bytes, but you're passing a char, and then two ints. If you make sure that you always pass a byte, everything works Commented May 17, 2021 at 10:28
  • 3
    "I have a byte Array that contains the char" - A byte array contains bytes, not chars. You should separate those two concepts in your mind. I suspect that if you search for a byte instead of an int or a char, it will work... Commented May 17, 2021 at 10:28
  • @canton7: There are overloads of Array.IndexOf that are generic, but if those fail, it'll fall back on the non-generic one, which I believe is what's happening here. Commented May 17, 2021 at 10:29
  • @JonSkeet Spotted and corrected mere seconds before your comment :) Commented May 17, 2021 at 10:29

1 Answer 1

2

You're trying to find an int value of 37 in a byte array. Byte arrays don't contain ints. You need to do a type cast:

int byteIndex = Array.IndexOf(bytesDataArray, (byte)37);
Sign up to request clarification or add additional context in comments.

1 Comment

oh sure, casting was the solution. Thanks :)

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.