Thread: hex to dec in c

  1. #1
    Registered User
    Join Date
    Jul 2007
    Posts
    19

    hex to dec in c

    I have a question, does anybody know about a function in C that will convert a char string like '2C' into a decimal number.

    Thanks.

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    2,129
    sscanf it in as a hex and sprintf it out as a dec.
    Last edited by robwhit; 08-07-2007 at 03:09 PM.

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    >does anybody know about a function in C that will convert a char string like '2C' into a decimal number.
    sscanf() or strtol(), take your pick.
    Code:
    #include <stdlib.h>
    #include <stdio.h>
    .
    .
       int num;
       
       if (sscanf("2C", "&#37;X", &num) != 1)
       {
          printf("Error during conversion.\n");
          return EXIT_FAILURE;
       }

  4. #4
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    An easier method is to use "strtol". It allows you to use any base you like, up to (I think) 36.

    Edit: Swoopy beat me to it.

    --
    Mats

  5. #5
    Registered User
    Join Date
    Jul 2007
    Posts
    19
    Thanks guys!!!!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 18
    Last Post: 03-26-2008, 09:01 AM
  2. hex to dec to binary
    By vijlak in forum C Programming
    Replies: 2
    Last Post: 10-26-2006, 09:38 AM
  3. Replies: 11
    Last Post: 03-24-2006, 11:26 AM
  4. Hex to Dec Problem
    By gqchynaboy in forum C Programming
    Replies: 14
    Last Post: 03-02-2005, 02:58 PM
  5. converting hex to dec
    By jibbles in forum C Programming
    Replies: 20
    Last Post: 08-07-2004, 11:40 PM