views:

253

answers:

2

I want to compare the first few bytes in byte[] with a string. How can i do this?

+8  A: 

You must know the encoding of the byte array to properly compare them.

For example, if you know your byte array is made of UTF-8 bytes, then you can create a string from the byte array:

System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
string s = enc.GetString(originalBytes);

Now you can compare string s to your other string.

Conversely, if you want to compare just the first few bytes, you can convert the string into a UTF8 byte array:

System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
byte[] b = enc.GetBytes(originalString);

Now you can compare byte array b to your other byte array.

There are several other encoding objects for ASCII, Unicode, etc. See the MSDN page here.

Jeff Meatball Yang
Isn't it more efficient to compare bytes instead of Strings?!
Josh Stodola
+1 Good edit ;)
Josh Stodola
@Josh: What do you think string comparison is? Worrying about this is probably a microoptimization.
Jason
I meant cast, not compare. My bad.
Josh Stodola
@Josh - Funny! As soon as I wrote my answer, I had exactly the same question as you did! (and in my head, it had a "?!" too - no joke!)
Jeff Meatball Yang
+1  A: 

use

byte [] fromString = Encoding.Default.GetBytes("helloworld");
TheVillageIdiot