Skip to content

Instantly share code, notes, and snippets.

@Autoplay1999
Created July 14, 2024 11:28
Show Gist options
  • Save Autoplay1999/a5db667a53aeeebbc5b102342a10848d to your computer and use it in GitHub Desktop.
Save Autoplay1999/a5db667a53aeeebbc5b102342a10848d to your computer and use it in GitHub Desktop.
#include "bin2c.hpp"
#include <sstream>
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <math.h>
void bin2c(std::string& out, const std::string& name, uint8_t* buffer, size_t size, size_t align) {
if (align % 2 != 0)
align = 1;
size_t i, mi, a;
bool rem = size != ceil(static_cast<double>(size) / align) * align;
std::stringstream ss;
std::string namebuf = name;
std::transform(name.begin(), name.end(), namebuf.begin(), ::toupper);
// ss << "#pragma once" << std::endl << std::endl;
ss << "#define " << namebuf << "_SIZE " << size << std::endl << std::endl;
ss << "static const " << (align == 2 ? "unsigned short" :
align == 4 ? "unsigned long" :
align == 8 ? "unsigned long long" :
"unsigned char") << " " << name << "[" << size / align + (rem ? 1 : 0) << "] = {" << std::endl << "\t";
for (i = 0, mi = size / align, a = 16 / align; i < mi; i++, buffer += align) {
if (i) {
ss << ", ";
if (i % a == 0) {
ss << std::endl << "\t";
}
}
switch (align) {
case 2: ss << "0x" << std::setfill('0') << std::setw(4) << std::uppercase << std::hex << *reinterpret_cast<uint16_t*>(buffer); break;
case 4: ss << "0x" << std::setfill('0') << std::setw(8) << std::uppercase << std::hex << *reinterpret_cast<uint32_t*>(buffer); break;
case 8: ss << "0x" << std::setfill('0') << std::setw(16) << std::uppercase << std::hex << *reinterpret_cast<uint64_t*>(buffer); break;
default: ss << "0x" << std::setfill('0') << std::setw(2) << std::uppercase << std::hex << static_cast<uint16_t>(*buffer); break;
}
}
if (rem) {
uint64_t tmp{};
memcpy(&tmp, buffer, size % align);
if (i) {
ss << ", ";
if (i % a == 0) {
ss << std::endl << "\t";
}
}
switch (align) {
case 2: ss << "0x" << std::setfill('0') << std::setw(4) << std::uppercase << std::hex << *reinterpret_cast<uint16_t*>(&tmp); break;
case 4: ss << "0x" << std::setfill('0') << std::setw(8) << std::uppercase << std::hex << *reinterpret_cast<uint32_t*>(&tmp); break;
case 8: ss << "0x" << std::setfill('0') << std::setw(16) << std::uppercase << std::hex << *reinterpret_cast<uint64_t*>(&tmp); break;
default: ss << "0x" << std::setfill('0') << std::setw(2) << std::uppercase << std::hex << static_cast<uint16_t>(*reinterpret_cast<uint8_t*>(&tmp)); break;
}
}
ss << std::endl << "};" << std::endl;
out = ss.str();
}
#pragma once
#include <cstdint>
#include <string>
void bin2c(std::string& out, const std::string& name, uint8_t* buffer, size_t size, size_t align = 4);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment