Skip to content

Instantly share code, notes, and snippets.

@Staubgeborener
Last active August 3, 2017 09:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Staubgeborener/b59580c6a84b2dacba2d9b8adaf39deb to your computer and use it in GitHub Desktop.
Save Staubgeborener/b59580c6a84b2dacba2d9b8adaf39deb to your computer and use it in GitHub Desktop.
Convert hexadecimal into binary
/* HexToBinary Headerfile
Convert Hexdata into binary
(C) 2017, Staubgeborener
https://github.com/Staubgeborener/ */
#include "HexToBinary.h"
#include <stdio.h>
#include <string.h>
HexToBinary::HexToBinary() {
}
char* HexToBinary::convert(char hexdec[])
{
size_t n = strlen(hexdec) - 1;
char buf[256];
char value[4];
for (int i = 0; i < n; i++) {
{
switch(hexdec[i])
{
case '0': strncpy(value, "0000", 4); break;
case '1': strncpy(value, "0001", 4); break;
case '2': strncpy(value, "0010", 4); break;
case '3': strncpy(value, "0011", 4); break;
case '4': strncpy(value, "0100", 4); break;
case '5': strncpy(value, "0101", 4); break;
case '6': strncpy(value, "0110", 4); break;
case '7': strncpy(value, "0111", 4); break;
case '8': strncpy(value, "1000", 4); break;
case '9': strncpy(value, "1001", 4); break;
case 'A': strncpy(value, "1010", 4); break;
case 'B': strncpy(value, "1011", 4); break;
case 'C': strncpy(value, "1100", 4); break;
case 'D': strncpy(value, "1101", 4); break;
case 'E': strncpy(value, "1110", 4); break;
case 'F': strncpy(value, "1111", 4); break;
case 'a': strncpy(value, "1010", 4); break;
case 'b': strncpy(value, "1011", 4); break;
case 'c': strncpy(value, "1100", 4); break;
case 'd': strncpy(value, "1101", 4); break;
case 'e': strncpy(value, "1110", 4); break;
case 'f': strncpy(value, "1111", 4); break;
default: printf("Something is wrong here...");
}
sprintf(buf + strlen(buf), "%s", value);
}
}
//Skip first four bytes (false, cause: buf + strlen(buf)
char* binary = buf + 4;
return binary;
}
#ifndef HexToBinary_h
#define HexToBinary_h
#include <stdint.h>
class HexToBinary
{
public:
HexToBinary();
char* convert(char hexdec[]);
};
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment