Using binary operators to compare byte[]s

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I'm trying to compare two byte[]'s. I think I have to use binary operators.
How can I tell if two bytes have the same value?


Also, I have a function that is returning a byte[] value. Is there a way to
see if the return value isnt null.

Thanks!
 
NathanV said:
I'm trying to compare two byte[]'s. I think I have to use binary operators.
How can I tell if two bytes have the same value?

just use ==
Also, I have a function that is returning a byte[] value. Is there a way to
see if the return value isnt null.

== null
Usually you should let it return an empty byte[] instead of null.
 
If you have broken down to byte arrays, it is quite easy to compare two
bytes. If you are trying to compare two bytes out of a Unicode char, or
similar, you will have to break down.

As for the byte array, check the length. If 0, you have nothing. You can
test null first, if you are ever going to return a null object, but it is
more common you will initialize before return (not always true, but more
common). Of course, this will break if you have set the array to a specific
length. You can also pull byte[0] and see if it is 0. This is fine, as long
as none of your bytes are 0. For most byte functions, 0 is a null char, so
it is not valid, but this is not always true.

--
Gregory A. Beamer
MVP; MCP: +I, SE, SD, DBA

*************************************************
Think outside the box!
*************************************************
 
public static bool ArraysEqual(byte[] ba1, byte[] ba2)
{
if ( ba1 == null )
throw new ArgumentNullException("ba1");
if ( ba2 == null )
throw new ArgumentNullException("ba2");

if ( ba1.Length != ba2.Length )
return false;

for(int i=0; i < ba1.Length; i++)
{
if ( ba1 != ba2 )
return false;
}
return true;
}
 
Back
Top