ZBLOG

C++ 实现二进制数据转换为base64字符串

在 C++ 中将二进制数据转换为 Base64 字符串可以通过手动实现编码算法或者使用现成的库。以下是一个简单的手动实现示例和使用流行库的示例。

手动实现 Base64 编码

以下是一个简单的 Base64 编码器:

#include <iostream>
#include <string>
#include <vector>

// Base64 字典
static const std::string base64_chars = 
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    "abcdefghijklmnopqrstuvwxyz"
    "0123456789+/";

// 检查是否是填充字符
bool is_base64(unsigned char c) {
    return (isalnum(c) || (c == '+') || (c == '/'));
}

// 将二进制数据转换为 Base64 字符串
std::string base64_encode(const unsigned char* data, size_t input_length) {
    std::string result;
    
    int i = 0;
    int j = 0;
    unsigned char char_array_3[3];
    unsigned char char_array_4[4];

    while (input_length--) {
        char_array_3[i++] = *(data++);
        if (i == 3) {
            // 将三字节转换为四个 Base64 字符
            char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
            char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
            char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
            char_array_4[3] = char_array_3[2] & 0x3f;

            for (i = 0; i < 4; i++)
                result += base64_chars.charAt(char_array_4[i]);
            
            i = 0;
        }
    }

    if (i) {
        for (j = i; j < 3; j++)
            char_array_3[j] = '\0';

        // 填充到四个字符
        char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
        char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
        char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
        
        for (j = i; j < sizeof(char_array_4); j++)
            char_array_4[j] = '=';

        for (j = 0; j < sizeof(char_array_4); j++)
            result += base64_chars.at(char_array_4[j]);
    }

    return result;
}

int main() {
    const std::string dataToEncode = "Hello, World!";
    
    // 将字符串转换为二进制数据(unsigned_char)
    std::vector<unsigned char> binaryData(dataToEncode.begin(), dataToEncode.end());
    
    // 编码成 Base64 字符串
    std::string encodedString = base64_encode(binaryData.data(), binaryData.size());

    std::cout << "Encoded string: " << encodedString << std::endl;

    return 0;
}

使用现成库

如果你想更方便地处理 Base64 编码,可以考虑使用如 libb64OpenSSL 或其他流行库。以 OpenSSL 为例,你可以这样做:

#include <iostream>
#include <openssl/bio.h>
#include <openssl/evp.h>

std::string base64_encode(const unsigned char* buffer, size_t length)
{
    BIO* bio;
    BIO* b64;
    BUF_MEM* bufferPtr;

    b64 = BIO_new(BIO_f_base64());
    
   // Create a memory buffer to hold the encoded string
   bio = BIO_new(BIO_s_mem());
   bio= BIO_push(b64, bio);

   // Encode the input buffer into the memory buffer
   BIO_set_flags(bio, BIO_FLAGS_BASE64_NO_NL); // Don't include newlines in the output.
   BIO_write(bio, buffer, length);
   BIO_flush(bio);
   BIO_get_mem_ptr(bio, &bufferPtr);

   // Create an output string from the encoded content in memory.
   std::string output(bufferPtr->data, bufferPtr->length);

   // Cleanup.
   BIO_free_all(bio);

   return output;
}

int main()
{
     const std::string dataToEncode("Hello, World!");
     std::string encodedString=base64_encode(reinterpret_cast<const unsigned char*>(dataToEncode.c_str()), dataToEncode.length());

     std::cout << "Encoded string: " << encodedString << std::endl;

     return EXIT_SUCCESS;
}

编译提示

确保在编译时链接 OpenSSL 库,例如使用 g++:

g++ -o your_program your_program.cpp -lssl -lcrypto

以上就是 C++ 中将二进制数据转换为 Base64 字符串的方法。你可以根据自己的需求选择手动实现或者使用库。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=21616

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?