Click here to Skip to main content
15,881,620 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to convert a bool array (for example {true, true, false} ) to a byte (00000110)
and after converting to integer, it would be 6.

How would I code this in C#? Thanks for answering...
Posted

Why go via a byte? You can go straight to uint. Unfortunately C#/.Net doesn't have bit booleans so I am not aware of a better approach than

uint BoolArrayToInt(bool[] bits){
 if(bits.Length > 32) throw new ArgumentException("Can only fit 32 bits in a uint");
 
 uint r = 0;
 for(int i = 0; i < bits.Length; i++) if(bits[i]) r |= 1 << (bits.Length - i);
 return r;
}
 
Share this answer
 
Comments
VigneshPT 9-Jan-12 11:30am    
Thanks for the reply... It was exactly what i was looking for.
Sergey Alexandrovich Kryukov 9-Jan-12 23:10pm    
Exactly, a 5.
--SA
Prajwal Prakash 19-Mar-13 6:17am    
i want to convert bool array into byte array such that bool[0] comes at byte[7] in c#. Can anyone please help me. Thank you
Take a look at the BitArray class, you can also look at my article which will compress the output integers here : Word Aligned Hybrid (WAH) Compression for BitArrays[^]
 
Share this answer
 
Comments
VigneshPT 9-Jan-12 11:31am    
Thanks for the reply. Found what i was looking for..

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900