Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BitConverter.ToString() in reverse? [duplicate]

Tags:

c#

.net

I have an array of bytes that I would like to store as a string. I can do this as follows:

byte[] array = new byte[] { 0x01, 0x02, 0x03, 0x04 };
string s = System.BitConverter.ToString(array);

// Result: s = "01-02-03-04"

So far so good. Does anyone know how I get this back to an array? There is no overload of BitConverter.GetBytes() that takes a string, and it seems like a nasty workaround to break the string into an array of strings and then convert each of them.

The array in question may be of variable length, probably about 20 bytes.

like image 862
Darren Oster Avatar asked Aug 04 '09 22:08

Darren Oster


2 Answers

You can parse the string yourself:

byte[] data = new byte[(s.Length + 1) / 3];
for (int i = 0; i < data.Length; i++) {
   data[i] = (byte)(
      "0123456789ABCDEF".IndexOf(s[i * 3]) * 16 +
      "0123456789ABCDEF".IndexOf(s[i * 3 + 1])
   );
}

The neatest solution though, I believe, is using extensions:

byte[] data = s.Split('-').Select(b => Convert.ToByte(b, 16)).ToArray();
like image 145
Guffa Avatar answered Nov 16 '22 22:11

Guffa


Not a built in method, but an implementation. (It could be done without the split though).

String[] arr=str.Split('-');
byte[] array=new byte[arr.Length];
for(int i=0; i<arr.Length; i++) array[i]=Convert.ToByte(arr[i],16);

Method without Split: (Makes many assumptions about string format)

int length=(s.Length+1)/3;
byte[] arr1=new byte[length];
for (int i = 0; i < length; i++)
    arr1[i] = Convert.ToByte(s.Substring(3 * i, 2), 16);

And one more method, without either split or substrings. You may get shot if you commit this to source control though. I take no responsibility for such health problems.

int length=(s.Length+1)/3;
byte[] arr1=new byte[length];
for (int i = 0; i < length; i++)
{
    char sixteen = s[3 * i];
    if (sixteen > '9') sixteen = (char)(sixteen - 'A' + 10);
    else sixteen -= '0';

    char ones = s[3 * i + 1];
    if (ones > '9') ones = (char)(ones - 'A' + 10);
    else ones -= '0';

    arr1[i] = (byte)(16*sixteen+ones);
}

(basically implementing base16 conversion on two chars)

like image 31
CoderTao Avatar answered Nov 16 '22 23:11

CoderTao