Thread: Function to convert an int to hex

  1. #1
    Registered User
    Join Date
    Oct 2011
    Location
    Ireland
    Posts
    30

    Function to convert an int to hex

    Hello.

    What are you looking to do when writing a function that will convert an into to it's hex version?

    I think I am right in saying I need to keep dividing the number by 16, until I get a remained of zero, yea? And the results will be the answer. Of course, I need to take into account the A-F. But Would this be done in a for loop?

    Seán

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    I think you mean, convert a decimal number to a hexadecimal number. Ints are neither; they are stored as binary. In source code, by default numbers are presumed to be decimal, but you can also use hex via 0x.

    If you want a string representation of an int in hexadecimal:
    Code:
    	unsigned int n = 0xdeadbeef;
    	char hex[sizeof(int)*2 + 1];
    	sprintf(hex, "%x", n);
    	puts(hex);
    	printf("%u\n", n);
    You don't have to use an unsigned type, I just like to say "deadbeef" and it won't fit otherwise.
    Last edited by MK27; 12-16-2011 at 11:44 AM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  3. #3
    Registered User
    Join Date
    Sep 2008
    Location
    Toronto, Canada
    Posts
    1,834
    Yes, o.fithcheallaig. Divide by 16, and each time you get a remainder which strips off the last hex digit. That way you are constructing the result from least-significant-digit to most-significant-digit. Indicates you save the digits in an array and display it out backwards. You can use a string such as "0123456789ABCDEF" to index into and display digits.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. how to convert this C function into C # code?
    By serendipity1276 in forum C# Programming
    Replies: 3
    Last Post: 11-08-2011, 09:44 AM
  2. need function to convert int to hex
    By sonnichs in forum C Programming
    Replies: 17
    Last Post: 08-11-2011, 07:26 PM
  3. Function: convert to notes
    By alice in forum C Programming
    Replies: 8
    Last Post: 05-03-2004, 02:56 AM
  4. Convert Char to Int Function
    By drdroid in forum C++ Programming
    Replies: 9
    Last Post: 02-19-2003, 12:53 PM
  5. help on a function of INT > CHAR convert!
    By SublicK in forum C++ Programming
    Replies: 2
    Last Post: 10-17-2001, 01:21 PM