|
-
Sep 3rd, 2007, 06:30 PM
#1
Thread Starter
Junior Member
Resolved-String to Byte[]?
OK, there's two ways to do this, but I only need the 2nd one.
1) Convert string to corresponding byte[] value (i.e "adslfI" == {0x44, 0x55)) (Not really true, but you get the idea) I don't need this one!
and
2) Convert it as if it was a byte array, so: in a textBox I put in: "44 AF 8E", and then it's converted to a byte array: {0x44, 0xAF, 0x8E}.
I've looked at various ASCII encoding and none get the job done, probably needs a for loop and some other crap...
Last edited by gamesguru; Sep 4th, 2007 at 02:13 PM.
-
Sep 3rd, 2007, 06:42 PM
#2
Re: String to Byte[]?
Code:
byte[] data = System.Text.Encoding.ASCII.GetBytes(myString);
GetString would do the equivalent in the other direction.
-
Sep 3rd, 2007, 06:59 PM
#3
Thread Starter
Junior Member
Re: String to Byte[]?
Does not work. I need this to convert it like so:
If I put "44 AF" into a textBox then convert it, the byte array results with the value {0x44, 0xAF}, not some completely irrelevant value...and anything else besides 0 1 2 3 4 5 6 7 8 9 A B C D E F will cause an unhandled exception. This is not the same as converting an integer value 0x44AF to byte array!
-
Sep 3rd, 2007, 08:36 PM
#4
Re: String to Byte[]?
Ah, it seems I didn't read your post carefully enough. The values returned by GetBytes are not irrelevant. Each byte represents the ASCII value of the corresponding character in the string. Hardly irrelevant but not what you want. What you want is this:
Code:
private byte[] GetBytes(string str)
{
string[] substrings = str.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
int length = substrings.Length;
byte[] bytes = new byte[length];
for (int index = 0; index < length; index++)
{
bytes[index] = Convert.ToByte(substrings[index], 16);
}
return bytes;
}
-
Sep 4th, 2007, 05:18 AM
#5
Thread Starter
Junior Member
Re: String to Byte[]?
That's exactly what I wanted, thanks a lot!
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|