0

I have a string and i changed it to hex values , so i want to store them in the Byte array , but it gives me error of "Input String is not correct format". here is my code :

        byte[] PlainText = new byte[16];
        byte[] MasterKey = new byte[16];
        string input = "Hello";
        char[] values = input.ToCharArray();
        int i =0;
        foreach (char letter in values)
        {
            int value = Convert.ToInt32(letter);
            string hexout = String.Format("{0:X}", value);
            PlainText[i++] = Convert.ToByte(hexout);
        }
3
  • 2
    Why bother with the int and string? Just convert directly to byte and be done with it. Commented May 15, 2014 at 4:52
  • it should be converted to int , i used the letter variable directly and it did convert nothing . Commented May 15, 2014 at 8:52
  • I am not saying use the letter variable directly, I am saying convert it directly to byte. Replace the three lines in your loop body with PlainText[i++] = Convert.ToByte(letter); or even PlainText[i++] = (byte)letter; Commented May 15, 2014 at 12:41

2 Answers 2

1

Change your intial code

    byte[] PlainText = new byte[16];
    byte[] MasterKey = new byte[16];
    string input = "Hello";
    char[] values = input.ToCharArray();
    int i =0;
     string hexout=string.empty;
    foreach (char letter in values)
    {
        int value = Convert.ToInt32(letter);
        hexout+= String.Format("{0:X}", value);

    }
    plaintext=StringToByteArray(hexout);

for converting hex to byte array

          public static byte[] StringToByteArray(String hex)
         {
      int NumberChars = hex.Length;
      byte[] bytes = new byte[NumberChars / 2];
       for (int i = 0; i < NumberChars; i += 2)
       bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
       return bytes;
      }

or

For parsing long string

   public static byte[] StringToByteArray(String hex)
 {
int NumberChars = hex.Length/2;
 byte[] bytes = new byte[NumberChars];
 using (var sr = new StringReader(hex))
{
for (int i = 0; i < NumberChars; i++)
  bytes[i] = 
    Convert.ToByte(new string(new char[2]{(char)sr.Read(), (char)sr.Read()}), 16);
 }
 return bytes;
}
Sign up to request clarification or add additional context in comments.

3 Comments

when i executed your firs code , it declares me an error :"Could not Find any recognizable digit" on the line 'bytes[i/2] = convert...'
@user3639111 now try this one
ok , so how can i verify that Plaintext array is now filled with same data just in Byte format? When i Console.Write nothing happens .
0
var bytes=System.Text.Encoding.UTF8.GetBytes(yourString);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.