Skip to content

Instantly share code, notes, and snippets.

@reicolina
Created November 7, 2015 15:25
Show Gist options
  • Save reicolina/3b66525b113679e35461 to your computer and use it in GitHub Desktop.
Save reicolina/3b66525b113679e35461 to your computer and use it in GitHub Desktop.
P1.6 Compression

P1.6 Compression: In P1.6 format, hexadecimal information is transferred: 3 hex bytes in 4 bytes in which the 7th bit is always 1 and the 8th bit (MSB) are reserved for parity. This type of compression is used in 'old school' devices such as the EMV modules inside some PIN entry devices (Payment PINPads). Here are VB methods for P1.6 encoding and decoding:

Friend Shared Function pP16Encode(ByVal yOriginalMessage As Byte()) As Byte()
    'Variable declarations
    Dim bitPosition As Integer = 1
    Dim origBitsPosition As Integer = 0
    Dim i As Integer

    'Convert the original bytes to a string of bits
    Dim sOrigBits As String = bytesToStringOfBits(yOriginalMessage)

    'Debug.Print(sOrigBits & vbCr)

    'get the new length for P1.6 encoded data
    Dim newLength As Integer = Math.Ceiling((yOriginalMessage.Length * 8) / 6)

    'do the P1.6 encoding
    Dim sNewBits((newLength * 8) - 1) As Char
    For i = 0 To sNewBits.Length - 1
        If bitPosition = 1 Then
            sNewBits(i) = "0"c
        ElseIf bitPosition = 2 Then
            sNewBits(i) = "1"c
        Else
            If origBitsPosition < sOrigBits.Length Then
                sNewBits(i) = sOrigBits(origBitsPosition)
                origBitsPosition = origBitsPosition + 1
            Else
                sNewBits(i) = "0"c
            End If
        End If
        bitPosition = bitPosition + 1
        If bitPosition > 8 Then
            bitPosition = 1
        End If
    Next

    'Convert the string of bits to bytes and return it to caller
    Return stringOfBitsToBytes(sNewBits)

End Function

Friend Shared Function pP16Decode(ByVal yEncodedMessage As Byte()) As Byte()
    Dim bitPosition As Integer = 1
    'Convert the encoded bytes to a string of bits
    Dim sEncodedMessage() As Char = bytesToStringOfBits(yEncodedMessage)
    'do the P1.6 decoding
    For i = 0 To sEncodedMessage.Length - 1
        If bitPosition = 1 Or bitPosition = 2 Then
            sEncodedMessage(i) = "X"c
        End If
        bitPosition = bitPosition + 1
        If bitPosition > 8 Then
            bitPosition = 1
        End If
    Next
    Dim sDecodedMessage As String = New String(sEncodedMessage)
    sDecodedMessage = sDecodedMessage.Replace("X"c, "")
    'Resize the decoded string accordingly
    sDecodedMessage = sDecodedMessage.Substring(0, (Math.Floor((yEncodedMessage.Length * 6) / 8)) * 8)
    'Convert to bytes and return decoded message to the caller
    Return stringOfBitsToBytes(sDecodedMessage)
End Function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment