If you are talking about alpha-numeric codes comprising any combination of
0-9 and A-Z then you can encode values from 0 to 1,679,615 inclusive (thats
1,679,616 combinations or 36 ^ 4 - 1). If you need more then you can add a-z
to your character set and you can then have 62 ^ 4 - 1 or 14,776,336
combinations from 0 to 14,776,335 inclusive.
For 0-9 and A-Z try:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button2.Click
Console.WriteLine(EncodeValue(0))
Console.WriteLine(EncodeValue(1))
Console.WriteLine(EncodeValue(1679615))
Console.WriteLine(DecodeValue("0000"))
Console.WriteLine(DecodeValue("0001"))
Console.WriteLine(DecodeValue("ZZZZ"))
End Sub
Private Function EncodeValue(ByVal value As Integer) As String
If value < 0 OrElse value > (36 ^ 4 - 1) Then Return String.Empty
Try
Dim _chars() As Char = New Char(35) {"0"c, "1"c, "2"c, "3"c, "4"c,
"5"c, "6"c, "7"c, "8"c, "9"c, "A"c, "B"c, "C"c, "D"c, "E"c, "F"c, "G"c,
"H"c, "I"c, "J"c, "K"c, "L"c, "M"c, "N"c, "O"c, "P"c, "Q"c, "R"c, "S"c,
"T"c, "U"c, "V"c, "W"c, "X"c, "Y"c, "Z"c}
Dim _result As String = String.Empty
For _i As Integer = 0 To 3
Dim _work As Integer = value \ CType(36 ^ _i, Integer) Mod 36
_result = _result.Insert(0, _chars(_work))
value -= _work * CType(36 ^ _i, Integer)
Next
Return _result
Catch
Return String.Empty
End Try
End Function
Private Function DecodeValue(ByVal value As String) As Integer
If value Is Nothing OrElse value.Length <> 4 Then Return -1
Try
Dim _chars() As Char = New Char(35) {"0"c, "1"c, "2"c, "3"c, "4"c,
"5"c, "6"c, "7"c, "8"c, "9"c, "A"c, "B"c, "C"c, "D"c, "E"c, "F"c, "G"c,
"H"c, "I"c, "J"c, "K"c, "L"c, "M"c, "N"c, "O"c, "P"c, "Q"c, "R"c, "S"c,
"T"c, "U"c, "V"c, "W"c, "X"c, "Y"c, "Z"c}
Dim _result As Integer = 0
For _i As Integer = 0 To 3
_result += Array.IndexOf(_chars, value.Chars(_i)) * CType(36 ^ (3 -
_i), Integer)
Next
Return _result
Catch
Return -1
End Try
End Function
For 0-9, A-Z and a-z, extend the character arrays and the loop limits
accordingly.