How to convert Textbox to Bytes?

user3206153

I have a textbox where a user can type bytes; 0x01, 0x02, 0x03 for example.

I want the textbox text to be added in here;

byte[] offset = new byte[] { **TEXTBOXINPUTHERE** };
Android.SetMemory(0x0248C8FC, offset);

How can I accomplish this? Many examples are converting the textbox input, which I don't want.

I want a user to send a offset to a memory address. So if a user TICKS the checkbox, it inputs the textbox text that has the offset. so instead of

byte[] buffer = new byte[] { 0x60, 0x00, 0x00, 0x00 }; 

I want it to be

byte[] buffer = new byte[] { textbox1.text };

User would input value like "0x01" or "0x01, 0x60, 0x00, 0x00" or any other.

Groo

If you input always consists of single-byte hex values prefixed with 0x, separated by a comma (i.e. "0x01, 0x02, 0x03"), then you can simply do something like:

var input = "0x01, 0x02, 0x03";

// no validation whatsoever
var array = input
    .Split(',')
    .Select(i => i.Trim().Replace("0x", ""))
    .Select(i => Convert.ToByte(i, 16))
    .ToArray();

Or, a slightly less strict version would split on different separator characters (e.g. commas, spaces, tabs):

private static byte[] GetByteArrayFromHexString(string input)
{
    return input
        .Split(new[] { ',',' ','\t' }, StringSplitOptions.RemoveEmptyEntries)
        .Select(i => i.Trim().Replace("0x", ""))
        .Select(i => Convert.ToByte(i, 16))
        .ToArray();
}

This should work for several different inputs, so that your users don't have to type all that unnecessary stuff:

// all these variants produce the same output
GetByteArrayFromHexString("0x01, 0x02, 0x03")  // --> new byte[] { 1, 2, 3 }
GetByteArrayFromHexString("0x01 0x02 0x03")    // --> new byte[] { 1, 2, 3 }
GetByteArrayFromHexString("01 02 03")          // --> new byte[] { 1, 2, 3 }

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related