Converting SHA-2 hash into alphanumeric hash (vb.net) - vb.net

I have SHA-2 hash values. Here's an example:
qlbQbEd8khe2vEYG9acKScUiVTC6y1UorkMvptATwwxkVApkOCUH7hwkncbi2TY78HrIeC19G8EHlaAmj6sBAwCxhF2TeOpmJ1+2OfbfXF+jMWUO74O7WHJuwoq+R5aKa0c2QYbyrcd/DWSprdkrF1gyz+RWVXYQug63aAhC0j0=
I need to convert these into an alphanumeric hash — that is, using only capital letters and numbers ("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"). The process has to be reversible for SHA-2 hash comparison.
The reason for this conversion is aesthetics. The resulting hash will be used as a license key, and has to be shorter and more easily readable and typeable.
I read that I could try to re-encode that hash into Base36, but I have been unsuccessful. Can anyone give any suggestions?

This code is an example for converting Base36 to/from Base26
Const Base36 As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Const Base26 As String = "abcdefghijklmnopqrstuvwxyz"
Function Num2Base(Vlu As Long, Base As String) As String
Dim A() As Integer = Nothing
Dim y As Integer = -1
Dim X As Long = Vlu
Dim Ln As Integer = Base.Length
Do While X > -1
y = y + 1
ReDim Preserve A(y)
A(y) = X Mod Ln
X = ((X - A(y)) / Ln) - 1
Loop
Dim res As String = ""
If y >= 0 Then
For Each d As Integer In A
res &= Mid(Base, d + 1, 1)
Next
End If
Return res
End Function
Function Base2Num(s As String, Base As String) As Long
If s.Length = 0 Then
Throw New Exception("'S' can not be empty")
End If
Dim res As Long = -1
Dim Ln As Integer = Base.Length
Dim x As Integer = 0
For Each c In s
res += (Base.IndexOf(c) + 1) * (Ln ^ x)
x += 1
Next
Return res
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim Num As Long = 1313
Dim b36 As String = Num2Base(Num, Base36) 'convert Num to base36
Dim b26 As String = Num2Base(Num, Base26) 'convert Num to base26
MessageBox.Show("Num:" & Num & vbCrLf & "ToBase36:" & b36 & vbCrLf & "ToBase26:" & b26, "Message 1")
Dim N36 As Long = Base2Num(b36, Base36) 'convert Base36 to Num
Dim N26 As Long = Base2Num(b26, Base26) 'convert Base26 to Num
MessageBox.Show("N36:" & N36 & vbCrLf & "N26:" & N26, "Message 2")
b26 = Num2Base(Base2Num(b36, Base36), Base26) 'convert Base36 to Base 26
MessageBox.Show("Base36 to Base 26 :" & b26, "Message 3")
b36 = Num2Base(Base2Num(b26, Base26), Base36) 'convert Base26 to Base 36
MessageBox.Show("Base26 to Base 36 :" & b36, "Message 4")
MessageBox.Show(Num2Base(1486154465904653, Base36), "Message 5")
End Sub
Unfortunately this code can not work with long strings(more than 12 chrs) due the limitation of the type Long,so you may need to split SHA-2 string to small parts

Related

I want to make a maths quiz on vb.net that uses bracket questions

So I've used visual basics (vb.net) for a bit now and understand some stuff. Right now I want to make a maths quiz that when I click a button it takes me to a new form and starts the quiz. When the quiz starts I want it so it gives the user random numbers and the user needs to answer it in a textbox and if correct it moves on to the next question (Basic, I should be able to do). IMPORTANT - my question is, there's a maths rule called BODMAS (Bracket.Order.Division.Multiply.Add.Subtract) and I want to add this rule into my coding instead of doing regular simple maths...
EXAMPLE question is 2 x (2+3) - 1 = ?
2 x 5 - 1 = ?
10 - 1 = ?
9 = 9
person writes answer to textbox and moves to next similar question
This is my first time using this but I wanted to write in-depth so people can understand. Please help me if you find a video explaining what I'm looking for or if someone has a file with a similar code I could download would be greatly appreciated!
Basically,you need to determine the range of numbers you use, and then match them randomly among '*', '/', '+', '-'. Then randomly insert brackets into it.
Private codeStr As String
Private Function GenerateMathsQuiz() As String
Dim r As Random = New Random()
Dim builder As StringBuilder = New StringBuilder()
'The maximum number of operations is five, and you can increase the number [5] to increase the difficulty
Dim numOfOperand As Integer = r.[Next](1, 5)
Dim numofBrackets As Integer = r.[Next](0, 2)
Dim randomNumber As Integer
For i As Integer = 0 To numOfOperand - 1
'All numbers will be random between 1 and 10
randomNumber = r.[Next](1, 10)
builder.Append(randomNumber)
Dim randomOperand As Integer = r.[Next](1, 4)
Dim operand As String = Nothing
Select Case randomOperand
Case 1
operand = "+"
Case 2
operand = "-"
Case 3
operand = "*"
Case 4
operand = "/"
End Select
builder.Append(operand)
Next
randomNumber = r.[Next](1, 10)
builder.Append(randomNumber)
If numofBrackets = 1 Then
codeStr = InsertBrackets(builder.ToString())
Else
codeStr = builder.ToString()
End If
Return codeStr
End Function
Public Function InsertBrackets(ByVal source As String) As String
Dim rx As Regex = New Regex("\d+", RegexOptions.Compiled Or RegexOptions.IgnoreCase)
Dim matches As MatchCollection = rx.Matches(source)
Dim count As Integer = matches.Count
Dim r As Random = New Random()
Dim numIndexFirst As Integer = r.[Next](0, count - 2)
Dim numIndexLast As Integer = r.[Next](1, count - 1)
While numIndexFirst >= numIndexLast
numIndexLast = r.[Next](1, count - 1)
End While
Dim result As String = source.Insert(matches(numIndexFirst).Index, "(")
result = result.Insert(matches(numIndexLast).Index + matches(numIndexLast).Length + 1, ")")
Return result
End Function
When you finish this, you will get a math quiz, then you need to know how to compile and run code at runtime.
Private Function GetResult(ByVal str As String) As String
Dim sb As StringBuilder = New StringBuilder("")
sb.Append("Namespace calculator" & vbCrLf)
sb.Append("Class calculate " & vbCrLf)
sb.Append("Public Function Main() As Integer " & vbCrLf)
sb.Append("Return " & str & vbCrLf)
sb.Append("End Function " & vbCrLf)
sb.Append("End Class " & vbCrLf)
sb.Append("End Namespace" & vbCrLf)
Dim CompilerParams As CompilerParameters = New CompilerParameters()
CompilerParams.GenerateInMemory = True
CompilerParams.TreatWarningsAsErrors = False
CompilerParams.GenerateExecutable = False
CompilerParams.CompilerOptions = "/optimize"
Dim references As String() = {"System.dll"}
CompilerParams.ReferencedAssemblies.AddRange(references)
Dim provider As VBCodeProvider = New VBCodeProvider()
Dim compile As CompilerResults = provider.CompileAssemblyFromSource(CompilerParams, sb.ToString())
If compile.Errors.HasErrors Then
Dim text As String = "Compile error: "
For Each ce As CompilerError In compile.Errors
text += "rn" & ce.ToString()
Next
Throw New Exception(text)
End If
Dim Instance = compile.CompiledAssembly.CreateInstance("calculator.calculate")
Dim type = Instance.GetType
Dim methodInfo = type.GetMethod("Main")
Return methodInfo.Invoke(Instance, Nothing).ToString()
End Function
Finally, you can use these methods like:
Private Sub GetMathQuizBtn_Click(sender As Object, e As EventArgs) Handles GetMathQuizBtn.Click
Label1.Text = GenerateMathsQuiz()
End Sub
Private Sub ResultBtn_Click(sender As Object, e As EventArgs) Handles ResultBtn.Click
If TextBox1.Text = GetResult(Label1.Text) Then
MessageBox.Show("bingo!")
TextBox1.Text = ""
Label1.Text = GenerateMathsQuiz()
Else
MessageBox.Show("result is wrong")
End If
End Sub
Result:

How can I get String values rather than integer

How To get StartString And EndString
Dim startNumber As Integer
Dim endNumber As Integer
Dim i As Integer
startNumber = 1
endNumber = 4
For i = startNumber To endNumber
MsgBox(i)
Next i
Output: 1,2,3,4
I want mo make this like sample: startString AAA endString AAD
and the output is AAA, AAB, AAC, AAD
This is a simple function that should be easy to understand and use. Every time you call it, it just increments the string by one value. Just be careful to check the values in the text boxes or you can have an endless loop on your hands.
Function AddOneChar(Str As String) As String
AddOneChar = ""
Str = StrReverse(Str)
Dim CharSet As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Dim Done As Boolean = False
For Each Ltr In Str
If Not Done Then
If InStr(CharSet, Ltr) = CharSet.Length Then
Ltr = CharSet(0)
Else
Ltr = CharSet(InStr(CharSet, Ltr))
Done = True
End If
End If
AddOneChar = Ltr & AddOneChar
Next
If Not Done Then
AddOneChar = CharSet(0) & AddOneChar
End If
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim S = TextBox1.Text
Do Until S = TextBox2.Text
S = AddOneChar(S)
MsgBox(S)
Loop
End Sub
This works as a way to all the codes given an arbitrary alphabet:
Public Function Generate(starting As String, ending As String, alphabet As String) As IEnumerable(Of String)
Dim increment As Func(Of String, String) = _
Function(x)
Dim f As Func(Of IEnumerable(Of Char), IEnumerable(Of Char)) = Nothing
f = _
Function(cs)
If cs.Any() Then
Dim first = cs.First()
Dim rest = cs.Skip(1)
If first = alphabet.Last() Then
rest = f(rest)
first = alphabet(0)
Else
first = alphabet(alphabet.IndexOf(first) + 1)
End If
Return Enumerable.Repeat(first, 1).Concat(rest)
Else
Return Enumerable.Empty(Of Char)()
End If
End Function
Return New String(f(x.ToCharArray().Reverse()).Reverse().ToArray())
End Function
Dim results = New List(Of String)
Dim text = starting
While True
results.Add(text)
If text = ending Then
Exit While
End If
text = increment(text)
End While
Return results
End Function
I used it like this to produce the required result:
Dim alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Dim results = Generate("S30AB", "S30B1", alphabet)
This gave me 63 values:
S30AB
S30AC
...
S30BY
S30BZ
S30B0
S30B1
It should now be very easy to modify the alphabet as needed and to use the results.
One option would be to put those String values into an array and then use i as an index into that array to get one element each iteration. If you do that though, keep in mind that array indexes start at 0.
You can also use a For Each loop to access each element of the array without the need for an index.
if the default first two string value of your output is AA.
You can have a case or if-else conditioning statement :
and then set 1 == A 2 == B...
the just add or concatenate your default two string and result string of your case.
I have tried to understand that you are looking for a series using range between 2 textboxes. Here is the code which will take the series and will give the output as required.
Dim startingStr As String = Mid(TextBox1.Text, TextBox1.Text.Length, 1)
Dim endStr As String = Mid(TextBox2.Text, TextBox2.Text.Length, 1)
Dim outputstr As String = String.Empty
Dim startNumber As Integer
Dim endNumber As Integer
startNumber = Asc(startingStr)
endNumber = Asc(endStr)
Dim TempStr As String = Mid(TextBox1.Text, 1, TextBox1.Text.Length - 1)
Dim i As Integer
For i = startNumber To endNumber
outputstr = outputstr + ", " + TempStr + Chr(i)
Next i
MsgBox(outputstr)
The First two lines will take out the Last Character of the String in the text box.
So in your case it will get A and D respectively
Then outputstr to create the series which we will use in the loop
StartNumber and EndNumber will be give the Ascii values for the character we fetched.
TempStr to Store the string which is left off of the series string like in our case AAA - AAD Tempstr will have AA
then the simple loop to get all the items fixed and show
in your case to achive goal you may do something like this
Dim S() As String = {"AAA", "AAB", "AAC", "AAD"}
For Each el In S
MsgBox(el.ToString)
Next
FIX FOR PREVIOUS ISSUE
Dim s1 As String = "AAA"
Dim s2 As String = "AAZ"
Dim Last As String = s1.Last
Dim LastS2 As String = s2.Last
Dim StartBase As String = s1.Substring(0, 2)
Dim result As String = String.Empty
For I As Integer = Asc(s1.Last) To Asc(s2.Last)
Dim zz As String = StartBase & Chr(I)
result += zz & vbCrLf
zz = Nothing
MsgBox(result)
Next
**UPDATE CODE VERSION**
Dim BARCODEBASE As String = "SBA0021"
Dim BarCode1 As String = "SBA0021AA1"
Dim BarCode2 As String = "SBA0021CD9"
'return AA1
Dim FirstBarCodeSuffix As String = Replace(BarCode1, BARCODEBASE, "")
'return CD9
Dim SecondBarCodeSuffix As String = Replace(BarCode2, BARCODEBASE, "")
Dim InternalSecondBarCodeSuffix = SecondBarCodeSuffix.Substring(1, 1)
Dim IsTaskCompleted As Boolean = False
For First As Integer = Asc(FirstBarCodeSuffix.First) To Asc(SecondBarCodeSuffix)
If IsTaskCompleted = True Then Exit For
For Second As Integer = Asc(FirstBarCodeSuffix.First) To Asc(InternalSecondBarCodeSuffix)
For Third As Integer = 1 To 9
Dim tmp = Chr(First) & Chr(Second) & Third
Console.WriteLine(BARCODEBASE & tmp)
If tmp = SecondBarCodeSuffix Then
IsTaskCompleted = True
End If
Next
Next
Next
Console.WriteLine("Completed")
Console.Read()
Take a look into this check it and let me know if it can help

variable longer than string

I am not really that good with vb.net, but i am facing a problem.
I have to convert a string into binary (thing i have done) but after that, I have to encrypt the string by combining it whith another string, also converted into binary.
Problem : I am broswing this result whith the help of a string y() , but the result has the dimension bigger that 32 bit and i get the error : {"Index was outside the bounds of the array."}
how cand i solve this?
Thanks
Dim preluare As String = TextBox5.Text ' the binary text i have to encrypt
Dim inter() As Char = preluare.ToCharArray
Dim b As Integer = TextBox5.Text.Count
Dim x As String = TextBox15.Text ' the key of encryption
Dim y() As Char = x.ToCharArray
Dim bb As Integer = TextBox15.Text.Count
' the key has to be the same lenght as the initial text
If b > x.Count Then
While x.Count < b
x = x + x
End While
End If
If x.Count > b Then
Dim w As Integer = x.Count
x = x.Trim().Substring(w - b)
End If
' xor operation
For i As Integer = 0 To b - 1
If inter(i) = "0" Then
'MsgBox(i)
If y(i) = "0" Then ' THIS IS WHERE I GET THE ERROR
TextBox10.Text = TextBox10.Text + "0"
Else
TextBox10.Text = TextBox10.Text + "1"
End If
Else
If inter(i) = "1" Then
If y(i) = "0" Then
TextBox10.Text = TextBox10.Text + "1"
Else
TextBox10.Text = TextBox10.Text + "0"
End If
End If
End If
Next
If you're sure the error was because size of y() bigger than 32 bit integer, how about using 64 bit integer data type as counter :
For i As Int64 = 0 To b - 1
.......
.......
Next
you can use unsigned variables like
uint16, uint32...

Comparing Strings

I would like to compare two strings in a vb.net windows application
Imports System.Windows
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim s As String = "$99"
Dim y As String = "$9899"
If s > y Then
MessageBox.Show("Hi")
End If
End Sub
End Class
Could anyone one correct the logic if there is any mistake in that?
You are comparing strings, not integers.
You could compare them as integers by replacing "$" with "" and then convert it to an integer.
Replace the $ to ""
s = s.Replace("$", "");
y = y.Replace("$", "");
Convert both of them to integers
Dim result1 As Integer
Dim result2 As Integer
result1 = Convert.ToInt32(s)
result2 = Convert.Toint32(y);
Then you can do
if (result1 > result2) { ... }
Dim sum1 As Int32 = 99
Dim sum2 As Int32 = 9899
'this works as expected because you are comparing the two numeric values'
If sum1 > sum1 Then
MessageBox.Show("$" & sum1 & " is greater than $" & sum2)
Else
MessageBox.Show("$" & sum2 & " is greater than $" & sum1)
End If
'if you really want to compare two strings, the result would be different than comparing the numeric values'
'you can work around this by using the same number of digits and filling the numbers with leading zeros'
Dim s As String = ("$" & sum1.ToString("D4")) '$0099'
Dim y As String = ("$" & sum2.ToString("D4")) '$9899'
If s > y Then
MessageBox.Show(s & " is greater than " & y)
Else
MessageBox.Show(y & " is greater than " & s)
End If
I recommend always to use Integers for numeric values, particularly if you want to compare them. You can format the values as string after you compared the numeric values.
What do you mean compare by length or content?
dim result as string
dim s as string = "aaa"
dim y as string = "bbb"
if s.length = y.length then result = "SAME" '= true
if s = y then result = "SAME" '= false
MessageBox.Show(result)

Convert a subnet mask into binary (octets) in vb.net

How can I convert a subnetmask into binary, so I'll end up with 32 digits?
I can convert it into Binary, using Convert.ToString(Long-to-convert, 2)
But a subnetmask of 255.255.255.0 returns(it returns it without the spaces though):
1111 1111 1111 1111 1111 1111 0
When I want it to be:
1111 1111 1111 1111 1111 1111 0000 0000
If you convert each byte separately then before the concatenate step you can do a PadLeft(8, '0') on each value. This would add the missing '0's.
'place this code in a separate module
'originally written by Dewayne Basnett in VBA - 1997
'converted to VB .Net - 2007
Option Strict On : Option Explicit On : Option Infer Off
Imports System.Net, System.Text
Module IP4Stuff
Const IPbrdcst As Long = 4294967295 '255.255.255.255 FF.FF.FF.FF
Dim aIP, aMSK As IPAddress
Dim nIP, nMSK, nNET, nHOST, addrs As Long 'numeric equivalents
Dim nCIDR, CIDR, x, y As Integer
Const shBits As Boolean = True 'True = show debug with bits using showBits function
Public Function ipRange(ByVal ipAddr As String, _
ByVal ipMask As String) As List(Of String)
'returns a list of all ip addresse on a given network
'
'ipRange("192.168.3.133", "255.255.254.0") '512 hosts - octet crossing
'
'255.255.254.0 is /23
'List(Of String) - partial output
'192.168.2.0
'192.168.2.1
'192.168.2.2
'...
'192.168.2.254
'192.168.2.255
'192.168.3.0
'192.168.3.1
'...
'192.168.3.253
'192.168.3.254
'192.168.3.255
'note
'first entry in list is THE network number
'last entry in list is the directed broadcast
'
nMSK = IPasNum(ipMask) 'get the Mask as number
CIDR = nCIDR 'get CIDR
nIP = IPasNum(ipAddr) 'get the IP address as number
nNET = IPnetAsNum(nIP, nMSK) 'get THE network number as number
addrs = nNET 'addrs = THE network number as number
nHOST = IPnumOfHosts(nMSK) 'get the number of hosts
If shBits Then
Debug.WriteLine("")
Debug.WriteLine("IP".PadRight(10, " "c) & showBits(nIP) & " " & ipAddr)
Debug.WriteLine("Mask".PadRight(10, " "c) & showBits(nMSK) & " " & ipMask)
Debug.WriteLine("Net".PadRight(10, " "c) & showBits(nNET) & " " & NumToIp(nNET))
Debug.WriteLine("Hosts".PadRight(10, " "c) & showBits(nHOST) & " " & nHOST.ToString)
Debug.WriteLine("CIDR".PadRight(10, " "c) & CIDR.ToString)
'Stop
End If
If nIP < 0 OrElse nMSK < 0 OrElse nNET = 0 OrElse nHOST = 0 Then
Return New List(Of String) 'error
End If
ipRange = New List(Of String)
For x As Long = 0 To nHOST
ipRange.Add(NumToIp(addrs)) 'add host to list
addrs += 1 'increment it
Next
End Function
Public Function IPnets(ByVal ipAddr As String, _
ByVal curCIDR As Integer, _
ByVal newCIDR As Integer) As List(Of String)
'returns a list of sub-nets using any IP in the current network,
'the current mask as CIDR and new mask as CIDR.
'192.168.3.? /23 to /25 - octet crossing
'
'IPnets("192.168.3.128", 23, 25)
'
'List(Of String)
'255.255.255.128
'192.168.2.0
'192.168.2.128
'192.168.3.0
'192.168.3.128
'
Dim curMASK, newMASK, netPlus1 As Long, numOfNets As Integer
nIP = IPasNum(ipAddr) 'get the IP address as number
If nIP < 0 OrElse curCIDR < 2 OrElse curCIDR > newCIDR OrElse newCIDR > 30 Then
Return New List(Of String) 'error
End If
IPnets = New List(Of String)
curMASK = MaskFromCidr(curCIDR) 'convert CIDR's to mask as number
newMASK = MaskFromCidr(newCIDR)
nHOST = IPnumOfHosts(newMASK)
netPlus1 = nHOST + 1 'used to add 1 to the network portion of the ip address
nNET = IPnetAsNum(nIP, curMASK) 'get THE network number as number
numOfNets = CInt(2 ^ (newCIDR - curCIDR)) 'number of networks
IPnets.Add(NumToIp(newMASK)) '<<<<<<<<<<<<<<<<<<<<< first entry in list is the new mask
If shBits Then
Debug.WriteLine("")
Debug.WriteLine("IP".PadRight(10, " "c) & showBits(nIP) & " " & ipAddr)
Debug.WriteLine("Network".PadRight(10, " "c) & showBits(nNET) & " " & NumToIp(nNET))
Debug.WriteLine("Cur. Mask".PadRight(10, " "c) & showBits(curMASK) & " " & NumToIp(curMASK))
Debug.WriteLine("New Mask".PadRight(10, " "c) & showBits(newMASK) & " " & NumToIp(newMASK))
Debug.WriteLine("Plus 1".PadRight(10, " "c) & showBits(netPlus1) & " " & NumToIp(netPlus1))
Debug.WriteLine("Num. Nets".PadRight(10, " "c) & numOfNets.ToString)
'Stop
End If
For x As Integer = 0 To numOfNets - 1
IPnets.Add(NumToIp(nNET))
'to get last address(broadcast) Dim BrdCst as long = nNET Or nHOST
nNET += netPlus1 'add one network number
Next
End Function
Private Function MaskFromCidr(ByVal CIDR As Integer) As Long
'x = 32 - CIDR
'z = (2^x)-1
'return z xor 255.255.255.255
MaskFromCidr = CLng(2 ^ ((32 - CIDR)) - 1) Xor IPbrdcst
End Function
Private Function IPnumOfHosts(ByVal IPmsk As Long) As Long 'a mask for the host portion
'255.255.255.0 XOR 255.255.255.255 = 255 so 0 to 255 is 256 hosts
IPnumOfHosts = IPmsk Xor IPbrdcst 'cacluate the number of hosts
End Function
Private Function IPnetAsNum(ByVal IPnum As Long, ByVal IPmsk As Long) As Long 'extract network from ip address
'192.168.2.113 AND 255.255.255.0 = 192.168.2.0
IPnetAsNum = IPnum And IPmsk 'calculate THE network number
End Function
Private Function IPasNum(ByVal AipAddr As String) As Long 'return -1 on error
If Not IPAddress.TryParse(AipAddr, aIP) Then 'convert string to IP
Return -1 'error
Else
IPasNum = IPtoNum(aIP) 'convert IP to number
If IPasNum = 0 Then
Return -1 'error
End If
End If
End Function
Private Function IPtoNum(ByVal theIP As IPAddress) As Long 'convert IP to number
Dim IPb() As Byte = theIP.GetAddressBytes 'get the octets
Dim theBit As Integer = 31 'work MSb to LSb
Dim addr As Long 'accumulator for address
nCIDR = 0
For x = 0 To 3 'four octets
For y = 7 To 0 Step -1 'with 8 bits each - duh
If (IPb(x) And CByte(2 ^ y)) = CByte(2 ^ y) Then 'if the bit is on
addr += CLng(2 ^ theBit) 'accumulate
nCIDR += 1 'count bits
End If
theBit -= 1 'decrement bit pos
Next
Next
Return addr
End Function
Private Function NumToIp(ByVal theIP As Long) As String 'convert number back to IP
Dim IPb(3) As Byte '4 octets
Dim theBit As Integer = 31 'work MSb to LSb
Dim addr As String 'accumulator for address
For x = 0 To 3 'four octets
For y = 7 To 0 Step -1 '8 bits
If (theIP And CLng(2 ^ theBit)) = CLng(2 ^ theBit) Then 'if the bit is on
IPb(x) += CByte(2 ^ y) 'accumulate
End If
theBit -= 1
Next
addr &= IPb(x).ToString & "." 'add current octet to string
Next
Return addr.TrimEnd("."c)
End Function
Private Function showBits(ByVal aNum As Long) As String
Dim strObits As New StringBuilder
strObits.Append(Convert.ToString(aNum, 2).PadLeft(32, "0"c))
For ix As Integer = 24 To 0 Step -8
strObits.Insert(ix, " ")
Next
showBits = strObits.ToString.Trim
End Function
End Module