Saturday, March 31, 2012

string to byte array conversion

I've a string similiar to "A509DE5B" (Length == 8 ) where each 2 characters are 1 hex number. How to convert such string into array of bytes (Lenght == 4)? In C# please, it's important...Byte.Parse()?

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystembyteclassparsetopic.asp
Hi LesioS!

I think you should try out something like this (I haven't tested it out myself, not sure if it works!!)


string sBytes = "A509DE5B";

Byte[] bytes = new Byte[(int)(sBytes.Length/2)];

int i = 0, j = 0;

while(i < sBytes.Length)
{
bytes[j] = Byte.Parse(str.Substring(i,2), NumberStyles.HexNumber);
i += 2;
}

Maybe it would work..

Good luck!
Oh, sorry, there's lots of mistakes in the code earlier code.

I tested this, and it worked, so be my guest! :)


string sBytes = "A509DE5B";
int i=0, j=0;
Byte[] bytes = new Byte[(int)(sBytes.Length/2)];
while(i < str.Length)
{
bytes[j] = Byte.Parse(sBytes.Substring(i,2), NumberStyles.HexNumber);
i += 2;
}


byte[] bytes = new byte[str.Length / 2];
for(int i = 0; i < str.Length / 2; i++)
bytes [i] = Byte.Parse(str.Substring(i * 2, 2), NumberStyles.HexNumber);

works fine... THX

But I wonder why there's no such function like ToCharArray for string object which produces byte array. In many cases functions from .NET Framework uses byte arrays, not char arrays :(

Try this:

// C# to convert a string to a byte array.
public static byte[] StrToByteArray(string str)
{
System.Text.ASCIIEncoding encoding=new System.Text.ASCIIEncoding();
return encoding.GetBytes(str);
}

Good luck!

Newbie


I have tried this

System.Text.

ASCIIEncoding encoding =new System.Text.ASCIIEncoding();string queryStringKey =ConfigurationManager.AppSettings["queryStringKey"];byte[] key = encoding.GetBytes(queryStringKey);return key;

to achieve this

//byte[] Key = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6 };

but it is not working. What am I not getting? Newbie

0 comments:

Post a Comment