Home >Backend Development >C++ >How to Encode and Decode Base64 Data in C ?
Base64 Decode Snippet in C
Base64 is a widely used encoding scheme that converts binary data into a string of printable ASCII characters. This is often necessary when transmitting binary data over channels that are not designed for its transmission, such as email or web pages.
Implementation Details
The provided code snippet implements both the encoding and decoding functionality of Base64 in C . The encoding function takes a buffer of binary data and its length, and returns a string containing the encoded data. The decoding function, on the other hand, takes a Base64-encoded string and returns a vector containing the decoded binary data.
To encode binary data, the snippet uses a series of steps:
Decoding Base64-encoded data follows a similar process:
Usage
To use the provided code snippet, include the "base64.h" header file in your C program and use the following functions:
Example
Here's an example of how to encode and decode Base64 data using the provided snippet:
#include "base64.h" int main() { // Binary data to encode std::vector<BYTE> data = {0x12, 0x34, 0x56, 0x78}; // Encode the data using Base64 std::string encodedData = base64_encode(&data[0], data.size()); // Print the encoded data std::cout << "Encoded Data: " << encodedData << std::endl; // Decode the Base64-encoded data std::vector<BYTE> decodedData = base64_decode(encodedData); // Print the decoded data std::cout << "Decoded Data:"; for (BYTE byte : decodedData) { std::cout << " " << std::hex << (int)byte; } std::cout << std::endl; return 0; }
This example will output the following:
Encoded Data: tEs= Decoded Data: 12 34 56 78
The above is the detailed content of How to Encode and Decode Base64 Data in C ?. For more information, please follow other related articles on the PHP Chinese website!