How to create a custom base with A-Z range

Mansour_Dalir 1,696 Reputation points
2024-04-08T04:10:40.88+00:00

Need 2 functions. One to convert number to string and another to convert string to number

Entering the number 1 will return A and the number 27 will return AA

And invert by giving AA to return 27 and AZ to return 52 and...

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,602 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jiachen Li-MSFT 27,166 Reputation points Microsoft Vendor
    2024-04-08T06:34:03.36+00:00

    Hi @Mansour_Dalir ,

    You can do this by circulating the modulo 26 or multiplying it by 26.

    Try the following code.

        Function NumberToString(number As Integer) As String
            Dim result As String = ""
            While number > 0
                Dim remainder As Integer = (number - 1) Mod 26
                result = Convert.ToChar(remainder + Asc("A")) & result
                number = (number - remainder) \ 26
            End While
            Return result
        End Function
    
        Function StringToNumber(str As String) As Integer
            Dim result As Integer = 0
            For Each c As Char In str
                result *= 26
                result += Asc(c) - Asc("A") + 1
            Next
            Return result
        End Function
    
    

    Best Regards.

    Jiachen Li


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful