Decimal to Hex

Discussion in 'C' started by bmsangati, Jun 13, 2012.

  1. bmsangati

    bmsangati New Member

    Joined:
    Jun 13, 2012
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    1. //Decimal to Hex value
    2. main()
    3. {
    4. char hex[16]={"0123456789ABCDEF"};
    5. int num,i=0,j;
    6. char result[];
    7. printf("Enter the Decimal No.\n");
    8. scanf("%d",&num);
    9. while(num)
    10. {
    11. result=hex[num%16];
      [*] num=num=num/16;
      [*] i++;
      [*] }
      [*] printf("Given num of the hex value is:");
      [*] for(j=i-1;j>=0;j--)
      [*] printf("%c",result[j]);
      [*] getch();
      [*] return 0;
      [*] }
     
  2. bmsangati

    bmsangati New Member

    Joined:
    Jun 13, 2012
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0

    :-(
     
  3. pein87

    pein87 Active Member

    Joined:
    Aug 6, 2010
    Messages:
    173
    Likes Received:
    47
    Trophy Points:
    28
    Occupation:
    Web Dev
    Location:
    Limbo
    I was going to code one for you but I found one online. Source

    Code:
    string toHexadecimal(int num)
    {
      int dividend, remain;
      string result = "";
      string hexArray[16];
      hexArray[0] = "0";
      hexArray[1] = "1";
      hexArray[2] = "2";
      hexArray[3] = "3";
      hexArray[4] = "4";
      hexArray[5] = "5";
      hexArray[6] = "6";
      hexArray[7] = "7";
      hexArray[8] = "8";
      hexArray[9] = "9";
      hexArray[10] = "a";
      hexArray[11] = "b";
      hexArray[12] = "c";
      hexArray[13] = "d";
      hexArray[14] = "e";
      hexArray[15] = "f";
      dividend = (int)num/16;
      remain = num%16;
      result = hexArray[remain];
      while (dividend != 0)
      {
        remain = dividend%16;
        dividend = (int)dividend/16;
        result = hexArray[remain]+result;
      }
      return result;
    }
    It's not meant to be a complete copy paste method but it is meant to show you what you were doing wrong. You made an array with 16 items but only assigned it one value. Each character needs to be a separate item in the array for this to work.
     
    Last edited: Jun 13, 2012

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice