Skip to content

Instantly share code, notes, and snippets.

@Yilmaz4
Created September 19, 2022 21:07
Show Gist options
  • Save Yilmaz4/f02d5509c4b443243b1cb53148b6e6ac to your computer and use it in GitHub Desktop.
Save Yilmaz4/f02d5509c4b443243b1cb53148b6e6ac to your computer and use it in GitHub Desktop.
Function to convert anything to binary representation with a null-terminated string in C++
template <typename type> char* to_binary(type* obj) {
char* binary = static_cast<char*>(malloc(sizeof(*obj) * 8 + (sizeof(*obj) - 1) + 1));
uint64_t idx = 0;
for (int64_t i = sizeof(*obj) - 1; i >= 0; i--) {
unsigned char byte = *((unsigned char*)(obj) + i);
auto* buffer = new char[8];
if (!binary || !buffer) {
return new char[1] {'\0'};
}
for (int64_t j = 7; j >= 0; j--) {
*(buffer + j) = ((byte & 1) ? '1' : '0');
byte >>= 1;
}
for (int64_t j = 0, k = 0; j < 8; k++, j++) {
*(binary + idx++) = *(buffer + k);
}
binary[idx++] = '\40';
delete[] buffer;
}
binary[idx] = '\0';
return binary;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment