Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1625
  • Last Modified:

Convert Hex to decimal in C/C++?

Can anyone provide me with a function that would convert a hex value to decimal in C/C++?

The following function converts from decimal to Hex:
string outputashex(unsigned long l) {
     char buffer[1024];
     itoa(l, buffer, 16);
     return buffer;
}

I need from hex to decimal.
Thanks a lot.

Ahmed
0
abayyari
Asked:
abayyari
1 Solution
 
akshayxxCommented:
  #include <stdlib.h>
            unsigned long strtoul(const char *S, char **PTR,
                int BASE);

            unsigned long _strtoul_r(void *REENT, const char *S,
                char **PTR, int BASE);

for more information see manual pageof strtoul
0
 
Tommy BraasCommented:
Try this;

#include <stdlib.h>

unsigned long inputfromhex(const char *str)
{
    return strtoul(str, NULL, 16);
}


If your string contains things other that a hexadecimal number, like "ad23Hi How are you?", you would want to pass in a pointer to get the position following the last digit in the number being converted from that string. The pointer would in the above example point to the 'H' in 'Hi'. E.g.

#include <stdlib.h>

unsigned long inputfromhex(const char *str, char **endPtr)
{
    return strtoul(str, endPtr, 16);
}

Hope this helps!
0
 
MafaldaCommented:
char hex_to_char(unsigned int i)
{
  char c = i % 256;
  return c;
}
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now