Computer Hope

Software => Computer programming => Topic started by: DaftHacker on July 25, 2013, 11:31:39 AM

Title: [Help] String/plain text to byte array
Post by: DaftHacker on July 25, 2013, 11:31:39 AM
Im trying to convert a string/plain text from a textbox to a byte array.

For example:
byte[] Bytes = new byte[] {0x00, 0x00, 0x00};

I want to do
byte[] Bytes = new byte[] {Textbox.Text};
And what I will put in the textbox will be 0x00 0x00 0x00
Title: Re: [Help] String/plain text to byte array
Post by: Fleexy on July 30, 2013, 12:58:19 PM
You should probably specify the language you're using, but I'm going to assume that's C# and that you're using Visual Studio.  I also don't fully understand what you're trying to do, but I'm pretty sure you want to get a byte array that contains the ASCII values of characters in a text box.

Code: [Select]
using Microsoft.VisualBasic;
char[] Characters = Textbox.Text.ToCharArray();
byte[] Bytes = new byte[Characters.Length - 1];
for (int i = 0; i < Characters.Length; i++) {
byte[i] = String.Asc(Characters[i]);
}
Title: Re: [Help] String/plain text to byte array
Post by: BC_Programmer on July 30, 2013, 04:43:53 PM
Code: [Select]
byte[] results = (from p in str.ToCharArray() select (byte)p).ToArray();

It looks like DaftHacker wants to go a bit further and actually have the textbox contain the Hex codes of each byte. Not a problem:

Code: [Select]
    String[] results = (from p in TextBox1.Text.ToCharArray() select String.Format("0x{0:X2}",(byte)p)).ToArray();
    TextBox1.Text = String.Join(" ", results);