Welcome guest. Before posting on our computer help forum, you must register. Click here it's easy and free.

Author Topic: [Help] String/plain text to byte array  (Read 4627 times)

0 Members and 1 Guest are viewing this topic.

DaftHacker

    Topic Starter


    Rookie

  • I am Daft
    • Yes
  • Computer: Specs
  • Experience: Experienced
  • OS: Windows 8
[Help] String/plain text to byte array
« 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

Fleexy



    Intermediate

  • OW NEXT TIME I SHOULD TURN IT OFF BEFORE SERVICING
  • Thanked: 2
    • Yes
    • Yes
  • Experience: Experienced
  • OS: Windows XP
Re: [Help] String/plain text to byte array
« Reply #1 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]);
}
I love .NET!

BC_Programmer


    Mastermind
  • Typing is no substitute for thinking.
  • Thanked: 1140
    • Yes
    • Yes
    • BC-Programming.com
  • Certifications: List
  • Computer: Specs
  • Experience: Beginner
  • OS: Windows 11
Re: [Help] String/plain text to byte array
« Reply #2 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);
I was trying to dereference Null Pointers before it was cool.