Question

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.

Was it helpful?

Solution

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^X can 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^X can be replaced with 1 << X.

In this context, here's what you want for your inner-most if-statement:

if ((intNumber & (1 << index)) != 0)
    a = a + "1";
else
    a = a + "0";

Plug that into a loop like you have in your bottom example, and you get this:

for (Int32 index = 7; index >= 0; index--)
    if ((intNumber & (1 << index)) != 0)
        bin = bin + "1";
    else
        bin = bin + "0";

Now, concatenating strings like this generates GC pressure, so you should probably either store these digits into a Char array, 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:

Char[] digits = new Char[8]; // change if you want more/fewer digits
for (Int32 index = 0; index < digits.Length; index++)
    if ((intNumber & (1 << index)) != 0)
        digits[digits.Length - 1 - index] = '1';
    else
        digits[digits.Length - 1 - index] = '0';
bin = new String(digits);

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:

String bin = Convert.ToString(intNumber, 2).PadLeft(8, '0');

This replaces the whole loop.

OTHER TIPS

It looks like it is using VB to do bitwise AND in this case, so perhaps:

if ( (1 & ( 2 ^ 1)) != 0)

However, this is a constant! Are you sure there isn't a variable in there somewhere?

2 ^ 1 is 3; 1 & 3 is 1; so this would always be true

(at least, under C#, where ^ is XOR; I'm told that in VB ^ is POWER, so 2 ^ 1 is 2; 1 & 2 is 0; so this would always be false...)

I don't understand the conditional syntax... Do you mean 1 & ( 2 ^ 1))? (Use only one ampersand for bitwise comparisons!) (but This is constant!)

but if a is a string, then

 a +=  Conditional?  "1": "0";

Try

if ( 1 & ( 2 ^ 1))
  a = a + "1";
else
  a= a+ "0";

Don't use the short circuiting and. Try this:

if (1 & (2 ^ 1) == 1)
{
    a = a + "1";
}
else
{
    a = a + "0";
}

Your post makes no sense whatsoever:

IF ( 1 AND ( 2 ^ 1)) Then 
 a = a + " 1" 
Else
  a = a + " 0"

2^1 = 2 = Math.Pow(2,1) 1 AND 2 = 1 & 2 = 0

This logic means that the result of the if will always be zero.

If I understand correctly what you want to do is in a loop do

if i is even
a = a + "0"
else
a = a+"1"

in this case it would be better if you just wrote

for (int i=7;i>=0;i--)
{
   bin+=(i % 2).ToString();
}

also for string concaternation in loop you should use StringBuilder class not + operator.

Just for reference, a more concise version of Lasse's final code:

Char[] digits = new Char[8]; // change if you want more/fewer digits
int index = digits.Length;
var x = intNumber;
do {
    digits[--index] = '0' + (x & 1);
    x >>= 1;
} while (index);
bin = new String(digits);

Basically, this takes advantage of the fact that we can just as easily shift the number right as shift the mask left. If we do things that way, the result of the AND operation is always the ones digit, which is the same digit we want in our string, so we just convert it to an ASCII character by adding '0' (or 48 or 0x30).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top