4.5 Encoding/Decoding Example

The following is the example of encoding and decoding the PropValue field in the TSProperty structure.

 #include <stdio.h>
 #include <tchar.h>
 #include <Windows.h>
  
 DWORD 
 EncodePropValue
 (
     __in BYTE* pbSource, 
     __in DWORD dwSourceLength, 
     __deref_out_bcount(*pdwDestLength) BYTE** ppbDest, 
     __out DWORD* pdwDestLength
     );
  
 DWORD 
 DecodePropValue
 (
     __in BYTE* pbSource,
     __in DWORD dwSourceLength,
     __deref_out_bcount(*pdwDestLength) BYTE** ppbDest,
     DWORD *pdwDestLength
     );
  
 int _tmain()
 {
     
     char* pPropValue = "ABCDE";
  
     char* pEncoded = NULL;
     DWORD cbEncoded = 0;
     char* pDecoded = NULL;
     DWORD cbDecoded = 0;
  
     //
     // Encoding a property value to be compatible with TSProperty structure.
     //
     EncodePropValue( PBYTE(pPropValue), (strlen(pPropValue)+1), (PBYTE*)&pEncoded, &cbEncoded );
  
     //
     // Decoding the encoded string.
     //
     DecodePropValue( PBYTE(pEncoded), cbEncoded, (PBYTE*)&pDecoded, &cbDecoded );
     printf("Decoded: %s\n", pDecoded);
  
     delete[] PBYTE(pEncoded);
     delete[] PBYTE(pDecoded);
  
 return 0;
 }
  
 DWORD 
 EncodePropValue
 (
     __in BYTE* pbSource, 
     __in DWORD dwSourceLength, 
     __deref_out_bcount(*pdwDestLength) BYTE** ppbDest, 
     __out DWORD* pdwDestLength
 )
 {
     *ppbDest = new BYTE[(dwSourceLength*2)+1];
  
     for(DWORD i=0; i<dwSourceLength; i++)
     {
         sprintf((char*)((*ppbDest)+(i*2)), "%02x", pbSource[i]);
     }
         
     *pdwDestLength = dwSourceLength*2;
  
     return 0;
 }
  
 #define MAPHEXTODIGIT(x) ( x >= '0' && x <= '9' ? (x-'0') :        \
                            x >= 'A' && x <= 'F' ? (x-'A'+10) :     \
                            x >= 'a' && x <= 'f' ? (x-'a'+10) : 0 )
  
 DWORD 
 DecodePropValue
 (
     __in BYTE* pbSource,
     __in DWORD dwSourceLength,
     __deref_out_bcount(*pdwDestLength) BYTE** ppbDest,
     DWORD *pdwDestLength
 )
 {
     *pdwDestLength = dwSourceLength/2;
     (*ppbDest) = new BYTE[*pdwDestLength];
  
     for(DWORD i=0; i<(*pdwDestLength); i++)
     {
              (*ppbDest)[i] = MAPHEXTODIGIT( pbSource[2*i]) * 16 +
                    MAPHEXTODIGIT( pbSource[2*i+1]);
     }
  
     return 0;
 }