Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean to integer conversion

Tags:

c#

Is there a way to covert from bool to integer without a conditional statement (e.g., if-statement)?

int intValue = boolValue ? 1 : 0;
like image 797
Razan Paul Avatar asked May 06 '26 20:05

Razan Paul


2 Answers

int intValue = Convert.ToInt32(boolValue));
like image 142
Shaharyar Avatar answered May 09 '26 09:05

Shaharyar


Despite the fact that nvoigt's answer is perfectly correct I can give you a few more examples JUST FOR FUN

NEVER! NEVER USE THIS CODE! IT IS PROVIDED JUST FOR FUN OR TO RESOLVE A DISPUTE WITH A (GOOD) FRIEND!)

At first method GetHashCode does the magic (as an implementation detail):

bool b = true;
int i = b.GetHashCode();

If you want some more esoteric approach.. hm.. you're welcome):

bool b = true;
int i = ~(b.ToString()[0] / 2) & 1;

REMEMBER! NEVER!

like image 34
Mikant Avatar answered May 09 '26 09:05

Mikant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!