2

I am trying to convert char array to byte. But I am getting the below error:

Cannot implicitly convert int to byte

public byte[] asciiToDecConversion(char[] asciiCharArray)
{
    byte[] decimalArray = new byte[10];
    const byte asciiFormat = 32;

    for (int j = 0; j < 10; j++)
    {
        decimalArray[j] = (Convert.ToByte(asciiCharArray[j]) - asciiFormat);
    }

    return decimalArray;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
sunshine
  • 39
  • 2
  • 8
  • 1
    @sunshine, you had several valid answers, so you should mark one as accepted so your post does not appear unanswered, and also you give credit to those who took the time to try to help you. – Andrew Oct 13 '16 at 17:48

3 Answers3

3

You need to cast to byte:

decimalArray[j] = (byte) (Convert.ToByte(asciiCharArray[j]) - asciiFormat);
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
  • 1
    Why `Convert.ToByte` for one cast and a direct cast for the other? Actually, that `Convert.ToByte` is not necessary at all. – Andrew Oct 07 '16 at 18:47
1

You should be able to cast it directly:

decimalArray[j] = (byte)(asciiCharArray[j] - asciiFormat);
K Richardson
  • 1,640
  • 1
  • 10
  • 14
0

You could do something as simple as this:

char[] charArray = "your string".ToCharArray(); // For example.
byte[] byteArray = charArray.Select(c => (byte)(c - 32)).ToArray();

Bear in mind that you code will fail if asciiCharArray has less than 10 elements.

Andrew
  • 7,602
  • 2
  • 34
  • 42