I have this If condition in VB6
If ( X AND ( 2 ^ Y)) Then a = a + ' 1' Else a = a + ' 0'
I want the same equivalent in C#
I tried doing like
if ( X && ( 2 ^ Y)) // ERROR: && can not be used between int to int a = a + '1'; else a = a + '0';
but this thing is giving me an error.
Here is my complete VB code that I want to convert into C#
For i = 7 To 0 Step -1 If intNumber And (2 ^ i) Then ' Use the logical 'AND' operator. bin = bin + '1' Else bin = bin + '0' End If Next
In above code intNumber could be any number.
Note: This answer has been heavily edited due to lack of information in original question. This version of the answer is now based on the updated question with enough information. For history, check the edit log.
Two things:
&&is used between Boolean expressions, to determine the logical AND-value^in C# means XOR, not raised-to-the-power-of. You didn’t ask a question about this but it was inevitable that you discovered that^didn’t appear to be doing its job.The
&&is easily handled, since it can be replaced with a single&instead, which has a dual meaning, depending on context. Either it is a full-evaluation logical AND operator (&&is a short-circuited one), or it is a bitwise operator, which is what you want here.The
^is different though. The most direct equivalent is Math.Pow, but in this case, a better alternative is available, bit-shift.The case of
2^Xcan be thought of as shift the 1-bit X positions to the left, and shift bits to the left has its own operator, the<<operator.So
2^Xcan be replaced with1 << X.In this context, here’s what you want for your inner-most if-statement:
Plug that into a loop like you have in your bottom example, and you get this:
Now, concatenating strings like this generates GC pressure, so you should probably either store these digits into a
Chararray, and construct the string afterwards, or use the StringBuilder class. Otherwise you’re going to build up 8 (from my example) differently sized strings, and you’re only going to use and keep the last one. Depending on circumstances this might not pose a problem, but if you call this code many times, it will add up.Here’s a better version of the final code:
However, and here’s the kicker. There is already a way to convert an Int32 value to a string full of binary digits in .NET, and it’s the Convert.ToString method. The only difference is that it doesn’t add any leading zeros, so we have to do that ourselves.
So, here’s the final code you should be using:
This replaces the whole loop.