BASE 85 Encoding VB Class

Base85 Encoding

Base85 Encoding

This is a BASE85 Encoding Visual Basic class that expands the text to be encoded by 4:5 i.e. uses 5 ASCII characters to represent 4 bytes with 80% accuracy. Used in Postscript and PDF documents. Useful if binary data needs to be persisted in ASCII text.

Currently it’s main uses are in Adobe PDF and PostScript file formats. It is also used by git to produce path of binary files i.e. used to encode the patch files. Here is their C implementation of Base85 encoding source code. This code extensively uses Modulus Operator to do the calculations and if-else statements. You can find more details on Modulus operator and some sample usage in this article. There is an article on conditional operations i.e. if-else in C.

Option Explicit

' BASE 85 Encoding VB Class
' ---------------------------------------------------------------
' 2002 Ed Preston - epreston@selectedsystems.com
'
' Interface
'
'   Encode(ByRef bArray() As Byte) As String
'   Decode(ByVal strIn As String) As Byte()
'
' Notes
'
'   Expands the text to be encoded by 4:5.  Used in Postscript
'   and PDF documents.  Useful if binary data needs to be
'   persisted in ASCII text, see also base 64 for email.
' ---------------------------------------------------------------

' Public properties
Public bolHeader As Boolean
Public bolPreserve As Boolean

Private intCount As Integer
Private intWidth As Integer
Private intPossition As Integer
Private dblCurValue As Double
Private strBuffer As String
Private bBuffer() As Byte
Private dblBufferPos As Double

' ----------------------------
' Public Methods
' ----------------------------

' Creates base85 encoded sections, if bolHeader is true then the
' "<~" is written to the buffer immediately before the base85
' encoded data.

Public Function Encode(ByRef bArray() As Byte) As String
    ' Encode here
    Dim d As Double

    ' Clear and reset current buffer
    strBuffer = vbNullString
    dblCurValue = 0
    intCount = 0
    intPossition = 0

    If bolHeader Then init85

    For d = 0 To UBound(bArray)
         put85 Val(bArray(d))
    Next

    ' Purge partial value if exits and add footer.
    cleanup85

    ' Return the buffer
    Encode = strBuffer
End Function

' Decodes byte array, if bolHeader is true then the routine will look
' for the "<~" headers and decode the sections. If bolHeader is false ' then the function assumes it has been passed a single bose85 section ' terminated with "~>"
Public Function Decode(ByVal strIn As String) As Byte()
    ' Decode here
    Dim x As Double
    Dim c As Integer
    Dim l As Double

    ' Get the length of the string
    l = Len(strIn)

    ' Clear current buffer
    dblBufferPos = 0
    ReDim bBuffer(l - 1)

    If bolHeader Then
        ' Cycle through the characters looking for a starting point.
        For x = 0 To l - 1

            c = Asc(Mid$(strIn, x + 1, 1))

            If c = Asc("<") Then
                ' We may have found one unless it is the last character
                If x <> l - 1 Then
                    ' It is a starting point if followed by a ~ character
                    If Asc(Mid$(strIn, x + 2, 1)) = Asc("~") And (x <> l - 2) Then
                        ' Found a starting point
                        x = decode85(strIn, x + 2, l)
                    Else
                        ' False alarm
                        If bolPreserve Then putbyte c
                    End If
                Else
                    ' Last character
                    If bolPreserve Then putbyte c
                End If
            Else
                ' Havent found starting point
                If bolPreserve Then putbyte c
            End If
        Next x

    Else
        ' We have been given a single base85 stream that should end with "~>"
        x = decode85(strIn, 0, l)
    End If

    ' Return the buffer
    Decode = bBuffer
End Function

' ----------------------------
' Private Methods
' ----------------------------

Private Sub Class_Initialize()
    ' Write header (Default)
    bolHeader = True

    ' Preserve non Base85 sections
    bolPreserve = True

    intCount = 0
    ' 72 characters seems like a nice round number
    intWidth = 72
    strBuffer = vbNullString
    intPossition = 0
    dblCurValue = 0
    dblBufferPos = 0
End Sub

' ----------------------------
' Support Routines
' ----------------------------

Private Function decode85(ByVal strIn As String, ByVal x As Double, ByVal l As Double) As Double
     Dim c As Integer
     Dim y As Double
     Dim dblValue As Double
     Dim intBytes As Integer

     ' Start decoding characters at possition x
     For y = x To l - 1

        c = Asc(Mid$(strIn, y + 1, 1))
        Select Case c
            Case 0 ' Asc(vbNullChar)
            Case 9 ' Asc(vbTab)
            Case 10 ' Asc(vbNewLine)
            Case 12 ' Asc(vbFormFeed)
            Case 13 ' Asc(vbCr)
            Case 32 ' Asc(vbBack)
                ' Whitespace formating characters, strip and forget

            Case Asc("z")
                ' Zero value found
                If intBytes <> 0 Then
                    ' Corrupt file?
                    ' z found inside ascii85 structure
                Else
                    putbyte (0)
                    putbyte (0)
                    putbyte (0)
                    putbyte (0)
                End If

            Case Asc("~")
                If Asc(Mid$(strIn, y + 2, 1)) = Asc(">") Then
                    ' Skip over footer
                    y = y + 2
                Else
                    ' Did not find the second character of the footer
                    y = y + 1
                End If

                If intBytes > 0 Then
                    intBytes = intBytes - 1
                    dblValue = dblValue + (85 ^ (4 - intBytes))
                    wput dblValue, intBytes
                End If

                Exit For

            Case Else
                If c < Asc("!") Then ' Corrupt file? ' Bad character in ascii85 region Err.Raise vbObjectError + 1, , "Bad character in ascii85 region" ElseIf c > Asc("u") Then
                    ' Corrupt file?
                    ' Bad character in ascii85 region
                    Err.Raise vbObjectError + 1, , "Bad character in ascii85 region"
                Else
                    dblValue = dblValue + (c - 33) * (85 ^ (4 - intBytes))
                    intBytes = intBytes + 1
                    If intBytes = 5 Then
                        wput dblValue, 4
                        intBytes = 0
                        dblValue = 0
                    End If
                End If

        End Select
     Next y

     ' Return the position at which we stopped decoding so the the
     ' main decode routine can continue to find other Base85 sections
     decode85 = y
End Function

' Break value down by shifting to the right.  We want the lower byte.
Private Sub wput(ByVal dblValue As Double, ByVal intBytes As Integer)
    Select Case intBytes
        Case 4
            putbyte (RShift(dblValue, 24) Mod 256)
            putbyte (RShift(dblValue, 16) Mod 256)
            putbyte (RShift(dblValue, 8) Mod 256)
            putbyte (dblValue Mod 256)
        Case 3
            putbyte (RShift(dblValue, 24) Mod 256)
            putbyte (RShift(dblValue, 16) Mod 256)
            putbyte (RShift(dblValue, 8) Mod 256)
        Case 2
            putbyte (RShift(dblValue, 24) Mod 256)
            putbyte (RShift(dblValue, 16) Mod 256)
        Case 1
            putbyte (RShift(dblValue, 24) Mod 256)
    End Select
End Sub

Private Sub encode85()
    Dim i As Integer
    Dim y As Integer
    Dim strArray(5) As Byte

    i = 5
    y = 0

    Do
        ' get the the modulus of the current value when devided by 85,
        ' rounding floating-point numbers to integers
        strArray(y) = dblCurValue Mod 85
        y = y + 1

        ' divide current value by 85 returning an integer result
        dblCurValue = dblCurValue \ 85
        i = i - 1
    Loop While i > 0

    ' Number of elements in array that have useful data
    i = intCount

    Do
        y = y - 1
        ' Add 33 or ASC value of ! character to make sure it is in the
        ' correct range.
        putchar Chr$(strArray(y) + 33)

        intPossition = intPossition + 1
        If (intPossition) >= intWidth Then
            ' At the end of the specified width
            intPossition = 0
            putchar vbNewLine
        End If

        i = i - 1
    Loop While i > -1
End Sub

' Cycle through the values shifting them, on the 4th value encode and
' write to output.
Private Sub put85(ByVal c As Double)

    intCount = intCount + 1
    Select Case intCount - 1
        Case 0
            dblCurValue = dblCurValue Or LShift(c, 24)
        Case 1
            dblCurValue = dblCurValue Or LShift(c, 16)
        Case 2
            dblCurValue = dblCurValue Or LShift(c, 8)
        Case 3
            dblCurValue = dblCurValue Or c
            If (dblCurValue = 0) Then
                putchar ("z")
                intPossition = intPossition + 1
                If (intPossition) >= intWidth Then
                    ' At the end of the specified width
                    intPossition = 0
                    putchar vbNewLine
                End If
            Else
                encode85
            End If
            dblCurValue = 0
            intCount = 0
    End Select
End Sub

' Create the header (Optional)
Private Sub init85()
    putchar "<~" ' Header intPossition = 2 
End Sub 
' Write any values still left to encode and attach footer 
Private Sub cleanup85() If (intCount > 0) Then encode85
    If (intPossition + 2) > intWidth Then putchar vbNewLine
    putchar "~>" ' Footer
End Sub

' Append characters to the string buffer
Private Sub putchar(ByVal strIn As String)
    ' Debug.Print "Putting character " & strIn
    strBuffer = strBuffer & strIn
End Sub

' Append bytes to the byte buffer
Private Sub putbyte(ByVal bIn As Byte)
    ' Debug.Print "Putting byte " & Chr(bIn)
    bBuffer(dblBufferPos) = bIn
    dblBufferPos = dblBufferPos + 1
End Sub

' Thank you Lewis Moten.  Why doen't VB support this?
Private Function LShift(ByVal pnValue As Double, ByVal pnShift As Double) As Double
    ' Equivilant to C's Bitwise << operator 
    LShift = pnValue * (2 ^ pnShift) 
End Function 

Private Function RShift(ByVal pnValue As Double, ByVal pnShift As Double) As Double 
' Equivilant to C's Bitwise >> operator
    RShift = pnValue \ (2 ^ pnShift)
End Function

Similarly there are Base64 encoding and decoding schemes which are commonly used to encode binary data.

M. Saqib: Saqib is Master-level Senior Software Engineer with over 14 years of experience in designing and developing large-scale software and web applications. He has more than eight years experience of leading software development teams. Saqib provides consultancy to develop software systems and web services for Fortune 500 companies. He has hands-on experience in C/C++ Java, JavaScript, PHP and .NET Technologies. Saqib owns and write contents on mycplus.com since 2004.
Related Post