Want to know the power-2 based numbers of x

  • Thread starter Thread starter Chad Miller
  • Start date Start date
C

Chad Miller

The only example I was able to find was written in PHP. Can anyone convert
to VB? Or give an example of how to perform this operation?

$x = 9124 ;

$n = 1 ;
while ( $x > 0 ) {
if ( $x & 1 == 1 ) {
echo $n, "\n" ;
}
$n *= 2 ;
$x >>= 1 ;
}

// Will output...
// 4
// 32
// 128
// 256
// 512
// 8192
 
Chad said:
The only example I was able to find was written in PHP. Can anyone
convert to VB? Or give an example of how to perform this operation?

An exact translation would be as follows:

\\\
Dim x As Integer
Dim n As Integer

x = 9124

n = 1
Do While x > 0
If (x And 1) = 1 Then
Debug.Print(CStr(n))
End If
n *= 2
x \= 2
Loop
///

This provides the same output as your PHP code.

HTH,
 
Chad said:
The only example I was able to find was written in PHP. Can anyone convert
to VB? Or give an example of how to perform this operation?

$x = 9124 ;

$n = 1 ;
while ( $x > 0 ) {
if ( $x & 1 == 1 ) {
echo $n, "\n" ;
}
$n *= 2 ;
$x >>= 1 ;
}

// Will output...
// 4
// 32
// 128
// 256
// 512
// 8192

This is basically just converting to binary and then listing the bits
that are set. the following code works, it may not be the best way to
do things, however:

Dim value As Integer = 9124
Dim bit As Integer = 0

While (2 ^ bit) <= value
Dim power As Integer = CInt(2 ^ bit)
If (value And power) = power Then
Console.WriteLine(power.ToString)
End If
bit += 1
End While
 
Back
Top