C++ function for hexadecimal conversion

Solved
Salut tout le monde, can someone tell me what the C++ function for converting to hexadecimal is? Thanks for any replies posted!

15 answers

  1. No need to do the conversion by hand! You're making it way too complicated for no reason. First comment: It's C++! Don't use the old C functions. #include <stdio.h> should be #include <cstdio>. If a standard library has a .h extension, it's an old C library. The standard C++ libraries simply don't have an extension. 2) Why use printf? Again, that's for C. Yes, it works in C++ but it's a bad habit. std::cout exists for C++. Moreover, the standard library already includes something that will greatly simplify your life... it's called std::hex.

    #include <iostream>

    int main()
    {
    std::cout << "Enter a number: ";
    int nb;
    std::cin >> nb;
    std::cout << "Here is this number in hexadecimal: "
    << std::hex << nb << std::endl;
    }

    It's that simple, you just have to include std::hex in a cout and the numbers will be displayed in hexadecimal representation. Much MUCH faster than a manual conversion. What to do if you want to assign a hexadecimal value to a variable in your program?

    int x = 0xFF;

    You just need to add 0x before the number, that's all. If you want me to write you a function to convert decimal to hexadecimal by yourself, just let me know, I'll write you a pretty fast one.

    -Aghaster

    www.planetcpp.info
    20
    1. Moderator
      You're right, I started from Hamzafes' response, I didn't even pay attention that the question was for C++.

      lami20j
      0
    2. Bonjour, j'ai un grand problème et je t'écris pour te demander de m'aider. Peux-tu m'envoyer un programme en C qui convertit la base décimale en bases binaire, octale et hexadécimale et vice versa s'il te plaît ? Aide-moi. Voici mon MSN : star_1987_4@hotmail.com
      0
  2. Ah, well then no problem. I wrote you a little prog that converts a std::string from decimal to hexadecimal. Improve it as you like (I didn't take into account if letters or characters other than numbers were entered). It's relatively fast, so here it is:

    #include <iostream>
    #include <sstream>
    #include <string>
    #include <cmath>

    int main()
    {
    std::cout << "Enter a number: ";
    std::string nb;
    std::cin >> nb;

    // Convert from std::string to integer
    int temp = 0;
    int len = nb.length();
    for(int i = 0; i < len; i++)
    {
    temp += (nb[i] - 48) * pow((float)10,len-i-1);
    }

    // And convert back to std::string in hexadecimal form!
    std::stringstream ss;
    ss << std::hex << temp;
    ss >> nb;

    std::cout << nb << std::endl; // There you go, it’s done.
    }

    Have fun! Don't hesitate if you have more questions.

    -Aghaster
    www.planetcpp.info
    7
    1. Moderator
      Hello,

      You can do something like this:
       int convert(char character) { char thing[]={'0', '1', '2', '3', '4', '5', '6', '7', '8', '9','a','b','c','d','e','f'}; int i; for (i=0;i<sizeof(thing);i++) { if (character == thing[i]){ return i; } } //No match found return -1; } 


      And if you need to convert 'a5' to 0xa5
      You should arrange to do:
      hex= (convert('a') << 4) + convert('5');

      Because for 'a', which corresponds to 10 *(16^1), you can also do 10 << 4.
      6
      1. this program does not work all the time:
        firstly, the size of the hex string converted is limited
        moreover, it does not allow converting a string containing spaces, as soon as the algorithm detects a space it stops and the rest of the string is not converted.
        How can I solve this problem? Please help me. If you have any ideas about this, feel free to reply to me, I would be very grateful.
        Thanks in advance.
        1
        1. Just a clarification: costs and other flows are the slowest things... if you want something quick, use sprintf().
          1
          1. Salam,
            I think the code below can help you:

            #include<stdio.h>

            void main()
            {
            char ch[33];
            int i;
            printf("\nDecimal\tHexadecimal\n----------------------------");
            for(i=7;i<20;i++)
            {
            sprintf(ch,"%x",i);
            printf("\n%d\t :\t%s",i,ch);
            }

            }

            God help me
            0
            1. Thank you, but I didn't want to display the result on the screen but to store it in a variable!
              0
              1. Moderator
                Hello,

                This is exactly what sprintf does.

                sprintf - writes formatted text into a string instead of the screen.
                sprint(Var,"Result =%X",i);
                The result is stored in the variable Var

                 sprintf(ch,"%x",i); 
                so hamzafes has stored the result in the variable ch
                0
              2. Moderator
                Yes, but he wants to convert "1a" to 0x1a
                It's the opposite of what sprintf() does.
                0
            2. Thank you for your responses, I will use sprintf.
              0
              1. Thank you Aghaster, I had forgotten that I was programming in C++ :P.
                0
                1. But there is a problem: std::hex only converts an int variable and not a string. What I wanted is to convert a std::string!
                  0
                  1. Why don't you use an istringstream for your string to decimal conversion function?
                    0
                    1. Here is the function I am now using:
                      std::string string_hex(std::string buffer){ // converts a string to a hexadecimal string std::ostringstream oss; // initializes a string stream to store output from std::hex for (std::string::const_iterator i = buffer.begin(); i != buffer.end(); ++i) // loops through each character { oss << std::hex << static_cast<int>(*i); // stores the output of std::hex in oss } return(oss.str()); }

                      and it works perfectly!!! Thank you for your responses.
                      0
                      1. how in version 6.0
                        0
                    2. Salut à tous, je cherche un algorithme qui fait la conversion de binaire vers les autres bases et vice versa. "S'il te plaît, je veux un algorithme qui soit écrit en Pascal." Et merci d'avance.
                      0
                      1. and post your messages in the right topics
                        0
                    3. A priori, no one offers the simple solution without an algorithm (...) that would allow displaying an int (e.g., 486) in binary (486d = 111100110b) (and not in hex, that's easy...).
                      I thought I would find a quick method that avoids having to deal with one or more intermediate conversions or loops, a conversion to hex, or reading bit by bit from an integer and converting it to char and concatenating it as you go ... pfff.
                      There must be a C++ method that does that directly... right?
                      0