Joshua
Joshua

Reputation: 4320

char* decimal to hexadecimal in little-endian

I have an issue where I am inputting an decimal argument to my code:

./a.out 650

and would like to simply convert the decimal value into hex and output it in a little-endian format:

0A28

My current solution has been to convert the char* to decimal using atoi (we can assume the input is decimal, no worry about error cases).

I have read that I could create an int* and cast it to the char*, something like this:

char* bar = argv[1];
int* foo = (char*)&bar;

and that iterating through it would produce the solution I needed, but I do not quite understand how that would work.

Upvotes: 1

Views: 1663

Answers (2)

chux
chux

Reputation: 154075

This should take the program's first parameter and print it out as a big endian hexadecimal number and little endian hexadecimal.

int main(int argc, char *argv[]) {
  if (argc != 2) return -1;
  char *endptr;
  unsigned long d = strtoul(argv[1], &endptr, 10);
  if (*endptr) {
    printf("Not a decimal number '%s'\n", argv[1]);
    return 1;
  }
  printf("%lX\n", d);  // normal
  do {
   printf("%02hhX", (unsigned char) d);  // little endian first
    d >>= 8;
  } while (d);
  printf("\n");
  return 0;
}

Upvotes: 2

Kerrek SB
Kerrek SB

Reputation: 477408

Like this:

#include <stdio.h>
#include <stdlib.h>

unsigned long int n = strtoul(argv[1], NULL, 0);
unsigned char const * p = (unsigned char const *)&n;

for (size_t i = 0; i != sizeof n; ++i)
    printf("%02X", p[i]);

To print the reverse endianness, use sizeof n - i - 1 in place of i.

Upvotes: 2

Related Questions