1

HI,

I'm reading a file in as hex and storing it in a string, what I need to do is then read in two chars at a time so say i have a string that contains

313233343536373839

I would need to read in 31 followed by 32 followed by 33

I'm new to c# and programming in general, my book has nothing on it and I can't find an example that explains it well for me, if you could advise me I would be greatful!

1
  • Sounds like a programming assignment. You say you're new to programming in general... do we need to go into loop structures or is just giving you a general idea good enough? Commented May 16, 2011 at 21:22

2 Answers 2

4

If you want to convert this hex string representation into a byte array you could use the following:

string str = "313233343536373839";
byte[] buffer = Enumerable
    .Range(0, str.Length)
    .Where(x => x % 2 == 0)
    .Select(x => Convert.ToByte(str.Substring(x, 2), 16))
    .ToArray();
Sign up to request clarification or add additional context in comments.

2 Comments

LOL for using Linq. As cool as this is, I'm guessing that it would probably be more beneficial for someone as new to things as he is to learn some of the more basic ways to do this rather than diving right into Linq... But, still cool none the less.
Not sure if I want to see this in my code-base.
1
string myString = "313233343536373839";

for (int i=0; i<myString.Length; i+=2)
{
    string myChars = myString.Substring(i, 2);
    // do something with myChars here ...
}

Was in the middle of posting this when Darin posted. Hadn't thought about doing it that way. Nice work Darin!

1 Comment

Thanks worked brilliant, thanks to everyone else that replied as well! :)

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.