The requirement is that there are 16 binary strings to save as byte arrays
such as String st = "0a000000", convert to byte after byte[0]=10,byte[1]=0,byte[2]=0,byte[3]=0
Net2.0 can use convert to convert a hexadecimal string to byte. The code is as follows: public static byte [] Writebytes1 (String sbytes)
... {
Stopwatch watch = new stopwatch ();
Watch. Reset ();
Watch. Start ();
Debug.Assert (sbytes.length% 2 = 0, "array length wrong");
int pos = 0;
int len = (SBYTES.LENGTH/2);
Byte[] B = new Byte[len];
int count = Sbytes.length;
for (int i = 0; i < count; i + + 2)
... {
B[pos] = Convert.tobyte (Sbytes.substring (i, 2), 16);
pos++;
}
Watch. Stop ();
Console.WriteLine ("{0}:{1}", "Writebytes1", watch.) Elapsed);
return b;
}
But I didn't think it was fast enough, and I found that the string I passed was 8 times the size of an integer, So we use the Convert.ToInt32 to convert the 8-bit length to the UInt32 number and bitconverter to the byte array, but the converted array contents are returned to my request content position, so the Array.reverse (array) method is used to turn the array back , and changed the code as follows: public static byte [] Writebytes2 (String sbytes)
... {
Stopwatch watch = new stopwatch ();
Watch. Reset ();
Watch. Start ();
Debug.Assert (sbytes.length% 2 = 0, "array length wrong");
Debug.Assert (sbytes.length% 8 = 0, "Array length is not suitable for this method");
int pos = 0;
int len = (SBYTES.LENGTH/2);
Byte[] B = new Byte[len];
int count = Sbytes.length;
Byte[] BT;
for (int i = 0; i < count; i + + 8)
... {
BT = Bitconverter.getbytes (Convert.ToInt32 (sbytes.substring (i, 8), 16));
Array.reverse (BT);
Bt. CopyTo (b, POS);
POS + 4;
}
Watch. Stop ();
Console.WriteLine ("{0}:{1}", "Writebytes2", watch.) Elapsed);
return b;
}
It didn't get much faster, and the strings lengthened and then slowed down, Immediately use reflector to look at the discovery is the array.reverse of the implementation of the speed down, there is no way can only write the integer to the byte method without Bitconverter and Array.reverse. The code is as follows: public static byte [] Writebytes3 (String sbytes)
... {
Stopwatch watch = new stopwatch ();
Watch. Reset ();
Watch. Start ();
Debug.Assert (sbytes.length% 2 = 0, "array length wrong");
Debug.Assert (sbytes.length% 8 = 0, "Array length is not suitable for this method");
int pos = 0;
int len =