The easiest string to/from byte array I've found(programmerramblings.blogspot.com)

submitted by phaymanphayman(3550) 4 years, 1 month ago

When looking for a utility function to convert from a hex string to a byte array, I found this example .. works a treat!

1 comment |category: |Views: 9

tags: another

new Add a live kick counter to your blog >> liveImage

You can even customize the image by choosing your own colors, and then clicking the button below to update the preview and the html code:

  • "Kick It" text
  • "Kick It" background
  • kick count text
  • kick count background
  • border

Simply copy and paste this HTML into your blog post.


Users who kicked this story:
Comments:

posted by yesthatmcgurkyesthatmcgurk(4063) 4 years, 1 month ago 0

1) Blogger blog without anonymous comments.

2) WTF
while (strInput.Length > i + 1)
{
long lngDecimal = Convert.ToInt32(strInput.Substring(i, 2), 16);
bytes[x] = Convert.ToByte(lngDecimal);
i = i + 2;
++x;
}

Lets check this out... Using a while to move through the string rather than a for() loop with a step of 2 is weird, but not too weird. What is weird is that he converts the substring to an int32, then casts it implicitly to a long, then converts that to a byte. Why not just:

byte[] result = new byte[data.Length / 2];
for (int i = 0; i < result.Length; i++)
{
result[i] = byte.Parse(
data.Substring(i * 2, 2),
NumberStyles.HexNumber);
}

3) The Bytes_To_String method (nice CamelCasing there, btw) isn't much better:
for (int x = 0; x <= bytes_Input.GetUpperBound(0); x++)
{
int number = int.Parse(bytes_Input[x].ToString());
strTemp += number.ToString("X").PadLeft(2, '0');
}

GetUpperBound? Wow, that's a new one on me. And he first casts the byte to a string, then converts this string to an int, then casts the int back to a string. Dude, that's crazy. BitConverter.ToString(data).Replace("-", ""); FTW.

Reply

information Login or create an account to comment on this story