0

I need somehow convert "xxx" to byte but i got exception

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

Additional information: Could not find any recognizable digits.

Is it possible "xxx" value convert to byte?

 byte tr  = (byte)(Convert.ToByte("xxx", 16) << 4);
Jannik
  • 2,058
  • 3
  • 25
  • 55

3 Answers3

1

This line (Convert.ToByte("xxx", 16) << 4) will return integer which is not convertible into string when parsing to byte that's why it throws the System.FormatException.

But there is already a good example of how to convert the string into byte[].

static byte[] GetBytes(string str)
{
    byte[] bytes = new byte[str.Length * sizeof(char)];
    System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
    return bytes;
}

Source of Example

Community
  • 1
  • 1
Leonel Sarmiento
  • 1,556
  • 2
  • 17
  • 42
  • than i got 120,0,120,0,120,0 but i with Encoding.UTF8.GetBytes("xxx") i can get 120,120,120 so maybe is better Encoding.UTF8.GetBytes("xxx")? –  Apr 25 '16 at 05:32
  • @IrmantasMedeišis It's up to you, the only benefit of my approach is you can still get the data and reconstruct the original string even if it contains an [invalid data](http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt) because it's only looking at the bytes. – Leonel Sarmiento Apr 25 '16 at 06:00
0

It is not possible to convert "xxx" to a byte. It simply is not the representation of any byte.

0

If you need to change a string into a byte array :

 byte[] toBytes = Encoding.ASCII.GetBytes("xxx");