No hay Problema
No hay Problema

Reputation: 883

Can somebody help me to revert this STR to BCD function?

I struggling to convert back the BCD to STR, if anyone quickly knows how to do it I really appreciate it.

Public Function strBCDToStr(ByVal shIn As Short) As String
    'BCD to Text
    Dim m_strTemp As String = ""
    For m_iLoop As Integer = 1 To 4
        m_strTemp = Chr((shIn Mod 16) + 48) & m_strTemp
        shIn = (shIn \ (16S))
    Next
    strBCDToStr = m_strTemp
End Function

Upvotes: 0

Views: 63

Answers (1)

Joel Coehoorn
Joel Coehoorn

Reputation: 415690

Since we're only dealing with short this works out as a simple mapping to standard hex notation. We can reverse it like this:

Public Function StrToShort(bcd As String) As Short
    bcd = bcd.Replace(":", "A").Replace(";", "B").Replace("<", "C").Replace("=","D").Replace(">", "E").Replace("?", "F")
    Return Convert.ToInt16(bcd, 16)
End Function

Technically I could even combine those two statements and make this method a one-liner.

See it here for every possible input up to the limit of fiddle:

https://dotnetfiddle.net/bvmdKC


We can also simplify the original code like so:

Public Function ShortToHexStr(input As Short) As String
    Return input.ToString("X").
        Replace("A", ":").
        Replace("B", ";").
        Replace("C", "<").
        Replace("D", "=").
        Replace("E", ">").
        Replace("F", "?"). 
        PadLeft( 4, "0"c)
End Function

Upvotes: 3

Related Questions