我們中的許多人在某個時間點偶然發現了用Base64 編碼的檔案或字串,但不知道從哪裡開始。在這種情況下,擁有一個有效的 C 程式碼片段來解碼此類訊息會有所幫助。
René Nyffenegger 編寫了一個實現,該實現採用二進位資料指標及其大小,並將原始資料轉換為 std::string與對應的 Base64 編碼資料。提供的解決方案包括一個頭檔(base64.h)和一個原始檔(base64.cpp)。
以下是最佳化後的base64.h頭檔:
#ifndef _BASE64_H_ #define _BASE64_H_ #include <vector> #include <string> typedef unsigned char BYTE; std::string base64_encode(BYTE const* buf, unsigned int bufLen); std::vector<byte> base64_decode(std::string const&); #endif</byte></string></vector>
這是修改後的base64.cpp原始檔:
#include "base64.h" #include <iostream> static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; static inline bool is_base64(BYTE c) { return (isalnum(c) || (c == '+') || (c == '/')); } std::string base64_encode(BYTE const* buf, unsigned int bufLen) { std::string ret; int i = 0; int j = 0; BYTE char_array_3[3]; BYTE char_array_4[4]; while (bufLen--) { char_array_3[i++] = *(buf++); if (i == 3) { char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) > 4); char_array_4[2] = ((char_array_3[1] & 0x0f) > 6); char_array_4[3] = char_array_3[2] & 0x3f; for(i = 0; (i '; char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) > 4); char_array_4[2] = ((char_array_3[1] & 0x0f) > 6); char_array_4[3] = char_array_3[2] & 0x3f; for (j = 0; (j base64_decode(std::string const& encoded_string) { int in_len = encoded_string.size(); int i = 0; int j = 0; int in_ = 0; BYTE char_array_4[4], char_array_3[3]; std::vector<byte> ret; while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) { char_array_4[i++] = encoded_string[in_]; in_++; if (i ==4) { for (i = 0; i > 4);</byte></iostream>
以上是如何在 C 中解碼 Base64 字串?的詳細內容。更多資訊請關注PHP中文網其他相關文章!