Hex

From miki
Revision as of 07:30, 4 October 2011 by Mip (talk | contribs) (→‎References)
Jump to navigation Jump to search

References

Many examples come from cplusplus.com and stackoverflow.com.

C

Read an integer from an hex string

Using atol

/* atol example */
#include <stdio.h>
#include <stdlib.h>

int main ()
{
  long int li;
  char szInput [256];
  printf ("Enter a long number: ");
  gets ( szInput );
  li = atol (szInput);
  printf ("The value entered is %d. The double is %d.\n",li,li*2);
  return 0;
}

Using strtol

/* strtol example */
#include <stdio.h>
#include <stdlib.h>

int main ()
{
  char szNumbers[] = "2001 60c0c0 -1101110100110100100000 0x6fffff";
  char * pEnd;
  long int li1, li2, li3, li4;
  li1 = strtol (szNumbers,&pEnd,10);
  li2 = strtol (pEnd,&pEnd,16);
  li3 = strtol (pEnd,&pEnd,2);
  li4 = strtol (pEnd,NULL,0);
  printf ("The decimal equivalents are: %ld, %ld, %ld and %ld.\n", li1, li2, li3, li4);
  return 0;
}

Using strtoul

Note there is also a strtoull

/* strtoul example */
#include <stdio.h>
#include <stdlib.h>

int main ()
{
  char szInput [256];
  unsigned long ul;
  printf ("Enter an unsigned number: ");
  fgets (szInput,256,stdin);
  ul = strtoul (szInput,NULL,0);
  printf ("Value entered: %lu. Its double: %lu\n",ul,ul*2);
  return 0;
}

Using sscanf

#include <stdio.h>
main()
{
    char s[] = "fffffffe";
    int x;
    sscanf(s, "%x", &x);
    printf("%u\n", x);
}