Base64.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #include "StdAfx.h"
  2. #include "Base64.h"
  3. CString CBase64::Encode(LPCTSTR szEncoding, int nSize)
  4. {
  5. //Base64编码字符集:
  6. CString m_sBase64Alphabet = _T("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
  7. char *szOutput;
  8. //计算空间
  9. int size = (nSize + 2) / 57 * 2;
  10. size += nSize % 3 != 0 ? (nSize - nSize % 3 + 3) / 3 * 4 : nSize / 3 * 4;
  11. szOutput = new char[size + 1];
  12. memset(szOutput, 0, size + 1);
  13. LPCTSTR szInput = szEncoding;
  14. int nBitsRemaining = 0, nPerRowCount = 0;//换行计数
  15. register int nBitStorage = 0, nScratch = 0;
  16. int i, lp, endlCount;
  17. for(i=0, lp=0, endlCount = 0; lp < nSize; lp++)
  18. {
  19. nBitStorage = (nBitStorage << 8) | (szInput[lp] & 0xff);//1 byte//the lowest-byte to 0 not cycle
  20. nBitsRemaining += 8;//读了一个字节,加八位
  21. do//nBitStorage"剩下的位"记录变量
  22. {
  23. nScratch = nBitStorage >> (nBitsRemaining - 6) & 0x3f;//提出最前的六位
  24. szOutput[i++] = m_sBase64Alphabet[nScratch];
  25. nPerRowCount++;
  26. if(nPerRowCount >= 76)
  27. {
  28. szOutput[i++] = '\r';
  29. szOutput[i++] = '\n';
  30. endlCount += 2;
  31. nPerRowCount = 0;
  32. }
  33. nBitsRemaining -= 6;
  34. }while(nBitsRemaining >= 6);
  35. }
  36. if(nBitsRemaining != 0)
  37. {
  38. //原数据最后多一个两个字节时进入,编码未结束nBitsRemaining!=0
  39. nScratch = nBitStorage << (6-nBitsRemaining);//空位补0
  40. nScratch &= 0x3f;
  41. szOutput[i++] = m_sBase64Alphabet[nScratch];
  42. nPerRowCount++;
  43. if(nPerRowCount >= 76)
  44. {
  45. szOutput[i++] = '\r';
  46. szOutput[i++] = '\n';
  47. endlCount += 2;
  48. nPerRowCount = 0;
  49. }
  50. }
  51. // Pad with '=' as per RFC 1521
  52. while((i - endlCount) % 4 != 0)
  53. {
  54. szOutput[i++] = '=';
  55. nPerRowCount++;
  56. if(nPerRowCount >= 76)
  57. {
  58. szOutput[i++] = '\r';
  59. szOutput[i++] = '\n';
  60. endlCount += 2;
  61. nPerRowCount = 0;
  62. }
  63. }
  64. CString strResult = szOutput;
  65. delete[] szOutput;
  66. return strResult;
  67. }