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
2009-07-08 03:31:56
Isn't it more efficient to compare bytes instead of Strings?!
Josh Stodola
2009-07-08 03:34:38
+1 Good edit ;)
Josh Stodola
2009-07-08 03:35:51
@Josh: What do you think string comparison is? Worrying about this is probably a microoptimization.
Jason
2009-07-08 03:36:26
I meant cast, not compare. My bad.
Josh Stodola
2009-07-08 03:37:09
@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
2009-07-08 03:38:54
+1
A:
use
byte [] fromString = Encoding.Default.GetBytes("helloworld");
TheVillageIdiot
2009-07-08 03:39:23