about decimal to hex progam

This is a discussion on about decimal to hex progam within the C Programming forums, part of the General Programming Boards category; hi everyone, I am trying to implement a program that converts a decimal into Hex, I am having some problem ...

  1. #1
    Registered User
    Join Date
    Apr 2002
    Posts
    28

    about decimal to hex progam

    hi everyone,

    I am trying to implement a program that converts a decimal into
    Hex, I am having some problem it doesn't do the right computation, can anyone see any abnormality of my implementaion.

    Here is the code:


    Code:
    code
    /* this function decimal number and transforms into hex */
    char HexConvert(int val)
    {
         char  *iter = val+10;
         
        
        while(iter>=val+2){
          /*compute hex digit*/
          if(val)
          {
              *iter = val%16;
              val/=16;
            
              if(*iter<10) /*output integer*/
              *iter+='0';
              return iter;
              else         /*output character*/
              *iter+=55; /* ASCII Value for A (=10) is 65 (=55+10) */
              return iter; 
          }
          else /*fill remaining hex array with zeros*/
            *iter = '0';
             return iter;
          iter--;
    
       }

  2. #2
    vVv
    Guest
    You have some problems with iter, because it points to a relatively random memory location with the address of val's content + 10.
    Also, there's actually no need for an if-test, just try something like;

    Code:
    #include <stdio.h>
    
    int main()
    {
      char buf[11],
           buf2[11],
           i = 0,
        j;
      int val = 255;
      while( val )
        buf[i] = "0123456789ABCDEF"[ val % 16 ], val /= 16, ++i;
      buf[i] = 0;
      for( i -= 1, j = 0; i > -1; i--, j++ )
        buf2[j] = buf[i];
      buf2[j] = 0;
      puts( buf2 );
      return 0;
    }

  3. #3
    Registered User
    Join Date
    Sep 2001
    Location
    Australia
    Posts
    212
    Code:
    int a=10;/*decimal*/
    printf("%d in hexadecimal is %x\n",a,a);

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 11
    Last Post: 03-24-2006, 10:26 AM
  2. hex to binary,hex to decimal
    By groovy in forum C Programming
    Replies: 2
    Last Post: 01-25-2006, 01:14 AM
  3. hex to decimal
    By caroundw5h in forum C Programming
    Replies: 5
    Last Post: 11-11-2004, 09:48 AM
  4. Converting decimal to hex
    By cobrakidd in forum C++ Programming
    Replies: 9
    Last Post: 02-06-2003, 10:37 AM
  5. Decimal vs. Hex
    By -leech- in forum C Programming
    Replies: 6
    Last Post: 02-18-2002, 11:51 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21