Skip to content

Instantly share code, notes, and snippets.

@RaJiska
Last active July 18, 2018 18:33
Show Gist options
  • Save RaJiska/447a6918a613eb6192f0bf3ea2e9328e to your computer and use it in GitHub Desktop.
Save RaJiska/447a6918a613eb6192f0bf3ea2e9328e to your computer and use it in GitHub Desktop.
Convert an hex-string little-endian to big-endian
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
enum arch
{
ARCH_NONE,
ARCH_X86 = 4 * 2,
ARCH_X86_64 = 8 * 2
};
typedef struct args
{
const char *str;
enum arch arch;
} args_t;
static void print_help(const char *myself, int ret)
{
printf("%s [OPTION]...\n\n"
"OPTIONS\n"
"\t-h\t\tShows this help message\n"
"\t-s [STRING]\tThe hex string to apply the reverse on\n"
"\t-a [ARCH]\tSets the arch to apply the reverse for, either"
"\"32\" (default) or \"64\"\n", myself);
exit(ret);
}
static bool arguments_are_valid(const char *myself, const args_t *args)
{
size_t str_len;
if (!args->str)
print_help(myself, EXIT_FAILURE);
str_len = strlen(args->str);
if (str_len == 0 || str_len % 2)
{
fprintf(stderr, "ERROR: Hex string cannot be odd\n");
return false;
}
if (args->arch == ARCH_NONE)
{
fprintf(stderr, "ERROR: Wrong architecture type\n");
return false;
}
if (str_len % args->arch)
{
fprintf(stderr, "ERROR: Wrong hex string padding for arch\n");
return false;
}
return true;
}
static void handle_options(args_t *args, int argc, char * const *argv)
{
int c;
while ((c = getopt(argc, argv, "+hs:a:")) != -1)
{
switch (c)
{
case 'h':
print_help(argv[0], EXIT_SUCCESS);
break;
case 's':
args->str = optarg;
break;
case 'a':
if (!strcmp(optarg, "32"))
args->arch = ARCH_X86;
else if (!strcmp(optarg, "64"))
args->arch = ARCH_X86_64;
break;
default:
print_help(argv[0], EXIT_FAILURE);
}
}
}
int main(int argc, char * const *argv)
{
args_t args = { 0 };
if (argc < 2)
print_help(argv[0], EXIT_FAILURE);
args.arch = ARCH_X86;
handle_options(&args, argc, argv);
if (!arguments_are_valid(argv[0], &args))
return EXIT_FAILURE;
for (size_t block = 0; args.str[block]; block += args.arch)
{
for (size_t byte = block + args.arch; byte > block; byte -= 2)
printf("%c%c", args.str[byte - 2], args.str[byte - 1]);
}
printf("\n");
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment