Home >Backend Development >C++ >How to Implement Base64 Decoding in C ?

How to Implement Base64 Decoding in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-26 20:06:12923browse

How to Implement Base64 Decoding in C  ?

Base64 Decode in C

Base64 is a widely used binary-to-text encoding scheme, employed in various applications, including data transmission and image storage. For convenience, many programming languages offer built-in Base64 encoding/decoding functionality. However, if you're working with C , you'll need to find a suitable library or implement your own code snippet.

A Modified Base64 Decoding Implementation

The following is a modified version of an existing Base64 decoding implementation in C :

Header File 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& encoded_string);

#endif

Source File 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) {
  ...  // Encoding implementation
  return ret;
}

std::vector<BYTE> base64_decode(std::string const& encoded_string) {
  ...  // Decoding implementation
  return ret;
}

Usage

To use the implementation, you can include the base64.h header and call the base64_decode function as follows:

std::string encodedData = "encoded_data_as_a_string";
std::vector<BYTE> decodedData = base64_decode(encodedData);

Additional Notes

  • The BYTE type is an alias for unsigned char.
  • The encoding and decoding functions operate on raw binary data and a string representation, respectively.
  • The encoding function generates a string with a URL-safe Base64 representation.
  • This snippet provides the necessary functionality for Base64 decoding in C , but please note that there are also other alternatives and libraries available that you may find more suitable for your specific needs.

The above is the detailed content of How to Implement Base64 Decoding in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn