Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# 7 binary literal for -1

Tags:

c#

.net

c#-7.0

I want to declare -1 literal using the new binary literal feature:

int x = 0b1111_1111_1111_1111_1111_1111_1111_1111;
Console.WriteLine(x);

However, this doesn't work because C# considers this as a uint literal and we get Cannot implicitly convert type 'uint' to 'int'... which is a bit strange for me since we deal with binary data.

Is there a way to declare -1 integer value using binary literal in C#?

like image 308
Alex Sikilinda Avatar asked May 08 '17 16:05

Alex Sikilinda


2 Answers

After trying some cases, I finally found out this one

int x = -0b000_0000_0000_0000_0000_0000_0000_0001;
Console.WriteLine(x);

And as result is printed -1.

If I understand everything correct they use sing flag for -/+ so when you put 32 1 you go into uint

like image 73
Samvel Petrosov Avatar answered Oct 17 '22 09:10

Samvel Petrosov


You can explicitly cast it, but because there's a constant term involved, I believe you have to manually specify unchecked:

int x = unchecked((int)0b1111_1111_1111_1111_1111_1111_1111_1111);

(Edited to include Jeff Mercado's suggestion.)

You can also use something like int x = -0b1 as pointed out in S.Petrosov's answer, but of course that doesn't show the actual bit representation of -1, which might defeat the purpose of declaring it using a binary literal in the first place.

like image 35
Joe Farrell Avatar answered Oct 17 '22 08:10

Joe Farrell