Tuesday, December 30, 2008

Long2IP in VB.Net and Narrowing Conversion

This is post #2 demonstrating how VB.Net makes things harder than C#.  I am receiving IP data as a type Long number.  It turns out that PHP has this helpful built-in function called long2ip that will do the translation back to the familiar “192.0.1.100” string for you. 

I found a few examples of VB code that could do the same, but as best I (and the compiler) could tell, they relied on functions that were not carried into VB.Net.  The problem is very simple though, or so I thought.  All I need to do is narrow the Long into a Byte and then shift the bits a Byte at a time.  In C# this is a piece of cake, but try as I might I could not convince the .Net CLR that I was intentionally overflowing the variable.  Despite trying every combination of Option Strict Off/On with CType, CByte, DirectCast, the runtime dutifully threw an OverflowException.  I was unable to find a way to do a narrowing conversion in VB.Net.

I gave up and created a separate C# class library for my helper class based on this code I found:

public static void ToBigEndian(long number, byte[] outputArray) {
 int length = outputArray.Length;
 outputArray[length - 1] = (byte)number;
 for (int i = length - 2; i >= 0; i--)

    outputArray[i] = (byte)(number >> (8 * (i + 1)));

}

With that, it was trivial to create my own version of Long2IP:

Public Function Long2IP(ByVal IP As Long) As String
  Dim
myIp(3) As Byte
 
IPHelp.ToBigEndian(IP, myIp)
  Return myIp(0) & "." & myIp(1) & "." & myIp(2) & "." & myIp(3)
End Function

 

 

No comments: