What is fastest way to convert bool to byte?
Posted
by
Amir Rezaei
on Stack Overflow
See other posts from Stack Overflow
or by Amir Rezaei
Published on 2011-02-12T21:58:07Z
Indexed on
2011/02/12
23:25 UTC
Read the original article
Hit count: 249
c#
What is fastest way to convert bool to byte?
I want this mapping: False=0, True=1
Note: I don't want to use any if statement.
Update: I don't want to use conditional statement. I don't want the CPU to halt or guess next statement.
I want to optimize this code:
private static string ByteArrayToHex(byte[] barray)
{
char[] c = new char[barray.Length * 2];
byte k;
for (int i = 0; i < barray.Length; ++i)
{
k = ((byte)(barray[i] >> 4));
c[i * 2] = (char)(k > 9 ? k + 0x37 : k + 0x30);
k = ((byte)(barray[i] & 0xF));
c[i * 2 + 1] = (char)(k > 9 ? k + 0x37 : k + 0x30);
}
return new string(c);
}
Update:
The length of the array is very large, it's in terabyte order! Therefore I need to do optimization if possible. I shouldn't need to explain my self. The question is still valid.
Update:
I'm working on a project and looking at others code. That's why I didn't provide with the function at first place. I didn't want to spend time on explaining for people when they have opinion about the code. I shouldn’y need to provide in my question the background of my work, and a function that is not written by me. I have started to optimize it part by part. If I needed help with the whole function I would asked that in another question. That is why I asked this very simple at the beginning. Unfortunately people couldn’t keep themselves to the question. So please if you want to help answer the question.
Update: For dose who want to see the point of this question. This example shows how two if statement are reduced from the code.
byte A = k > 9 ; //If it was possible (k>9) == 0 || 1
c[i * 2] = A * (k + 0x30) - (A - 1) * (k + 0x30);
© Stack Overflow or respective owner