I’m writing a Binary file converter in which I need to convert 1-6 byte arrays into int (short-long) values. At the moment I’m using following three functions, I want to know is there anyway to improve the performance?
private string byteToShortParse(byte[] recordData, int offset, int length)
{
byte[] workingSet = new byte[2];
Buffer.BlockCopy(recordData, offset, workingSet, 0, length);
return (BitConverter.ToInt16(workingSet, 0).ToString());
}
private string byteToIntParse(byte[] recordData, int offset, int length)
{
byte[] workingSet = new byte[4];
Buffer.BlockCopy(recordData, offset, workingSet, 0, length);
return (BitConverter.ToInt32(workingSet, 0).ToString());
}
private string byteToLongParse(byte[] recordData, int offset, int length)
{
byte[] workingSet = new byte[8];
Buffer.BlockCopy(recordData, offset, workingSet, 0, length);
return (BitConverter.ToInt32(workingSet, 0).ToString());
}
Edit2:
I suppose if the number of bytes you need to convert to int is variable length (which does seem strange), I suggest doing it this way:
Now you have one function, no Buffer.BlockCopy and it supports any length.
Edit1:
You could use unsafe code such as:
But this is what BitConverter does internally, so I don’t think you will gain any performance
Why are you copying the bytes into
workingSet? You could just:return BitConverter.ToInt32(recordData, offset).ToString()I guess that yields a performance boost since you don’t have to call Buffer.BlockCopy every time 😛