Entero a cadena hexadecimal en C++


¿Cómo convertir un entero a una cadena hexadecimal en C++?

Puedo encontrar algunas formas de hacerlo, pero en su mayoría parecen dirigidas hacia C. No parece que haya una forma nativa de hacerlo en C++. Sin embargo, es un problema bastante simple; tengo un int que me gustaría convertir en una cadena hexadecimal para imprimir más tarde.

Author: Wolf, 2011-02-24

13 answers

Use <iomanip>std::hex. Si imprime, simplemente envíelo a std::cout, si no, use std::stringstream

std::stringstream stream;
stream << std::hex << your_int;
std::string result( stream.str() );

Puedes anteponer el primer << con << "0x" o lo que quieras si lo deseas.

Otras manips de interés son std::oct (octal) y std::dec (volver al decimal).

Un problema que puede encontrar es el hecho de que esto produce la cantidad exacta de dígitos necesarios para representarlo. Puede usar setfill y setw esto para eludir la problema:

stream << std::setfill ('0') << std::setw(sizeof(your_type)*2) 
       << std::hex << your_int;

Así que finalmente, sugeriría tal función: {[18]]}

template< typename T >
std::string int_to_hex( T i )
{
  std::stringstream stream;
  stream << "0x" 
         << std::setfill ('0') << std::setw(sizeof(T)*2) 
         << std::hex << i;
  return stream.str();
}
 157
Author: Kornel Kisielewicz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-28 14:40:38

Para hacerlo más ligero y más rápido sugiero usar relleno directo de una cuerda.

template <typename I> std::string n2hexstr(I w, size_t hex_len = sizeof(I)<<1) {
    static const char* digits = "0123456789ABCDEF";
    std::string rc(hex_len,'0');
    for (size_t i=0, j=(hex_len-1)*4 ; i<hex_len; ++i,j-=4)
        rc[i] = digits[(w>>j) & 0x0f];
    return rc;
}
 27
Author: AndreyS Scherbakov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-31 02:54:33

Use std::stringstream para convertir enteros en cadenas y sus manipuladores especiales para establecer la base. Por ejemplo así:

std::stringstream sstream;
sstream << std::hex << my_integer;
std::string result = sstream.str();
 19
Author: phlipsy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-02-24 05:32:00

Simplemente imprímalo como un número hexadecimal:

int i = /* ... */;
std::cout << std::hex << i;
 11
Author: Etienne de Martel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-02-24 05:30:59

Puede probar lo siguiente. Está funcionando...

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;

template <class T>
string to_string(T t, ios_base & (*f)(ios_base&))
{
  ostringstream oss;
  oss << f << t;
  return oss.str();
}

int main ()
{
  cout<<to_string<long>(123456, hex)<<endl;
  system("PAUSE");
  return 0;
}
 7
Author: Mahmut EFE,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-07 18:08:10
int num = 30;
std::cout << std::hex << num << endl; // This should give you hexa- decimal of 30
 3
Author: Mahesh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-02-24 05:31:30

Para aquellos de ustedes que se dieron cuenta de que muchos / la mayoría de los ios::fmtflags no funcionan con std::stringstream todavía les gusta la idea de plantilla que Kornel publicó hace mucho tiempo, lo siguiente funciona y es relativamente limpio:

#include <iomanip>
#include <sstream>


template< typename T >
std::string hexify(T i)
{
    std::stringbuf buf;
    std::ostream os(&buf);


    os << "0x" << std::setfill('0') << std::setw(sizeof(T) * 2)
       << std::hex << i;

    return buf.str().c_str();
}


int someNumber = 314159265;
std::string hexified = hexify< int >(someNumber);
 1
Author: Kevin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-05 20:11:09

Código para su referencia:

#include <iomanip>
...
string intToHexString(int intValue) {

    string hexStr;

    /// integer value to hex-string
    std::stringstream sstream;
    sstream << "0x"
            << std::setfill ('0') << std::setw(2)
    << std::hex << (int)intValue;

    hexStr= sstream.str();
    sstream.clear();    //clears out the stream-string

    return hexStr;
}
 1
Author: parasrish,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-18 20:22:51

Esta pregunta es antigua, pero me sorprende por qué nadie mencionó boost::format:

cout << (boost::format("%x") % 1234).str();  // output is: 4d2
 1
Author: s4eed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-20 07:01:37

Solo echa un vistazo a mi solución,[1] que copié textualmente de mi proyecto, por lo que hay un documento de API en alemán incluido. Mi objetivo era combinar flexibilidad y seguridad dentro de mis necesidades reales:[2]

  • no 0x prefijo añadido: quien llama puede decidir
  • automática deducción de anchura : menos escribir
  • ancho explícito control: ampliación para formatear, reducción (sin pérdidas) para ahorrar espacio
  • , capaz de tratar con long long
  • restringido a tipos integrales : evita sorpresas por conversiones silenciosas
  • facilidad de comprensión
  • sin límite codificado
#include <string>
#include <sstream>
#include <iomanip>

/// Vertextet einen Ganzzahlwert val im Hexadezimalformat.
/// Auf die Minimal-Breite width wird mit führenden Nullen aufgefüllt;
/// falls nicht angegeben, wird diese Breite aus dem Typ des Arguments
/// abgeleitet. Funktion geeignet von char bis long long.
/// Zeiger, Fließkommazahlen u.ä. werden nicht unterstützt, ihre
/// Übergabe führt zu einem (beabsichtigten!) Compilerfehler.
/// Grundlagen aus: http://stackoverflow.com/a/5100745/2932052
template <typename T>
inline std::string int_to_hex(T val, size_t width=sizeof(T)*2)
{
    std::stringstream ss;
    ss << std::setfill('0') << std::setw(width) << std::hex << (val|0);
    return ss.str();
}

[1] basado en la respuesta de Kornel Kisielewicz
[2] Traducido al lenguaje de CppTest, esto es lo que se lee:

TEST_ASSERT(int_to_hex(char(0x12)) == "12");
TEST_ASSERT(int_to_hex(short(0x1234)) == "1234");
TEST_ASSERT(int_to_hex(long(0x12345678)) == "12345678");
TEST_ASSERT(int_to_hex((long long)(0x123456789abcdef0)) == "123456789abcdef0");
TEST_ASSERT(int_to_hex(0x123, 1) == "123");
TEST_ASSERT(int_to_hex(0x123, 8) == "00000123");
 0
Author: Wolf,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-06 12:24:47

Lo hago:

int hex = 10;      
std::string hexstring = stringFormat("%X", hex);  

Echa un vistazo a SO respuesta de iFreilicht y el archivo de encabezado de plantilla requerido desde aquí GIST!

 0
Author: CarpeDiemKopi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-06 16:18:52

La respuesta de Kornel Kisielewicz es genial. Pero una ligera adición ayuda a detectar casos en los que está llamando a esta función con argumentos de plantilla que no tienen sentido (por ejemplo, float) o que podrían resultar en errores desordenados del compilador (por ejemplo, tipo definido por el usuario).

template< typename T >
std::string int_to_hex( T i )
{
  // Ensure this function is called with a template parameter that makes sense. Note: static_assert is only available in C++11 and higher.
  static_assert(std::is_integral<T>::value, "Template argument 'T' must be a fundamental integer type (e.g. int, short, etc..).");

  std::stringstream stream;
  stream << "0x" 
         << std::setfill ('0') << std::setw(sizeof(T)*2) 
         << std::hex << i;

         // Optional: replace above line with this to handle 8-bit integers.
         // << std::hex << std::to_string(i);

  return stream.str();
}

He editado esto para agregar una llamada a std::to_string porque los tipos enteros de 8 bits (por ejemplo, std::uint8_t valores pasados) a std::stringstream se tratan como caracteres, lo que no le da el resultado que desea. Pasando tales enteros a std::to_string los maneja correctamente y no daña las cosas al usar otros tipos enteros más grandes. Por supuesto, es posible que sufra un ligero golpe de rendimiento en estos casos, ya que la llamada std::to_string es innecesaria.

Nota: Simplemente habría agregado esto en un comentario a la respuesta original, pero no tengo el representante para comentar.

 0
Author: Loss Mentality,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-25 18:47:34

Prueba esto:

#include<iostream>

using namespace std;

int main() {
    int *a = new int;//or put a number exept new int
                     //use * for pointer
    cin >> *a;
    cout << a; //if integer that is made as pointer printed without *, than it will print hex value
    return 0;
    //I hope i help you
}
 -1
Author: Marko Bošnjak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-10 14:43:17