user5581557
user5581557

Reputation: 213

Check if C# byte array contains a String

is there a way to check if the bytes in a byte[] is a valid string, so if it contains ASCII characters only.

if (isValidASCII(myByteArray)) {
....
}

something that I could use like the above example but with functionality.

Upvotes: 0

Views: 8126

Answers (4)

Abhay Dixit
Abhay Dixit

Reputation: 1018

First you can convert your bytes array into string using this

System.Text.Encoding.ASCII.GetString(BytesArray);

then check if it is valid or not.

Upvotes: -1

ioncodes
ioncodes

Reputation: 124

string asciiString = Encoding.ASCII.GetString(Encoding.ASCII.GetBytes(BYTEVARIABLE));

now check if the the string has some chars that have been changed to '?' if yes it wasn't ASCII only.

Upvotes: -3

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186688

Well, if

contains ASCII characters only

means symbols with codes within [32..127] (corresponding characters are [' '..'~']) - standard ASCII table characters with command ones excluded:

Boolean isAscii = myByteArray.All(b => b >= 32 && b <= 127)

However, a valid string being defined like that can well apper to be

 "$d|1 ?;)y" // this is a valid ASCII characters based string

or alike. If you want to wrap this simple Linq into a method:

  public static bool isValidASCII(IEnumerable<byte> source) {
    if (null == source)
      return true; // or false, or throw exception

    return source.All(b => b >= 32 && b <= 127);
  }

  ...

  if (isValidASCII(myByteArray)) {
     ...
  }

Upvotes: 6

Martijn
Martijn

Reputation: 12102

Literally answering your question:

Yes. It's not only very easy, it's trivial:

Boolean isValidAscii(Byte[] bytes) {
  return true;
}

This is most likely not what you're looking for.

ASCII is a table that maps each byte to a character. By definition every byte represents a valid ASCII character.

So the question really is, what are you looking for? What is a valid ASCII character in your opinion.

Once you define that, it's easy to code:

Boolean iFindThisAValidAsciiCharacter(Char c) {
  //your logic here
}

Boolean isValidAscii(Byte[] bytes) {
  return bytes.forAll((Byte b) => iFindThisAValidAscciCharacter( (char)b))
}

The trick, of course, is in your definition of what you consider valid.

I advice you to take a step back, and consider why you want "valid ascii" in the first place. In this brave new world of internationalization and unicode, it sounds very unlikely that what you are trying to do is going to accomplish what you want to accomplish.

Upvotes: 1

Related Questions