Integer To hex string w C++
Jak przekonwertować liczbę całkowitą na ciąg szesnastkowy w C++?
Mogę znaleźć kilka sposobów, aby to zrobić, ale głównie wydają się być ukierunkowane na C. nie wydaje się, że jest natywny sposób, aby to zrobić w C++. Jest to jednak dość prosty problem; mam int
, który chciałbym przekonwertować na ciąg szesnastkowy do późniejszego drukowania.
13 answers
Użyj <iomanip>
' s std::hex
. Jeśli drukujesz, po prostu wyślij go do std::cout
, jeśli nie, to użyj std::stringstream
std::stringstream stream;
stream << std::hex << your_int;
std::string result( stream.str() );
Możesz poprzedzić pierwszą <<
<< "0x"
lub cokolwiek chcesz, jeśli chcesz.
Inne manipy są std::oct
(ósemkowe) i std::dec
(z powrotem do dziesiętnego).
Jednym z problemów, które możesz napotkać, jest fakt, że daje to dokładną liczbę cyfr potrzebnych do jej reprezentowania. Możesz użyć setfill
i setw
w celu obejścia problem:
stream << std::setfill ('0') << std::setw(sizeof(your_type)*2)
<< std::hex << your_int;
Na koniec proponuję taką funkcję:
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();
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-28 14:40:38
Aby było lżejsze i szybsze proponuję użyć bezpośredniego wypełnienia Sznurka.
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;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-31 02:54:33
Użyj std::stringstream
do konwersji liczb całkowitych na ciągi znaków i specjalnych manipulatorów do ustawiania bazy. Na przykład tak:
std::stringstream sstream;
sstream << std::hex << my_integer;
std::string result = sstream.str();
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-02-24 05:32:00
Po prostu wydrukuj go jako liczbę szesnastkową:
int i = /* ... */;
std::cout << std::hex << i;
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-02-24 05:30:59
Możesz spróbować następujących. To działa...
#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;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-07 18:08:10
int num = 30;
std::cout << std::hex << num << endl; // This should give you hexa- decimal of 30
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-02-24 05:31:30
Dla tych z Was, którzy zorientowali się, że wiele / większość ios::fmtflags
nie działa z std::stringstream
, ale podobnie jak pomysł szablonu, który Kornel zamieścił dawno temu, działa i jest stosunkowo czysty:
#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);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-05 20:11:09
Kod w celach informacyjnych:
#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;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-18 20:22:51
To pytanie jest stare, ale dziwi mnie, dlaczego nikt nie wspomniał boost::format
:
cout << (boost::format("%x") % 1234).str(); // output is: 4d2
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-20 07:01:37
Wystarczy spojrzeć na moje rozwiązanie,[1] że dosłownie skopiowałem z mojego projektu, więc nie niemiecki jest API doc zawarte. Moim celem było połączenie elastyczności i bezpieczeństwa w ramach moich rzeczywistych potrzeb:[2]
-
no
0x
prefix dodano: rozmówca może zdecydować - automatyczne odliczenie szerokości: mniej typowania
- explicit width Kontrola: Rozszerzanie dla formatowania, (bezstratne) kurczenie się, aby zaoszczędzić miejsce
- zdolny do radzenia sobie z
long long
- ograniczone do typów całkowych : unikaj niespodzianek przez ciche konwersje
- łatwość zrozumienia
- no hard-coded limit
#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] na podstawie odpowiedzi Kornela Kisielewicza
[2] przetłumaczone na język CppTest , tak brzmi:
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");
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-06 12:24:47
Robię:
int hex = 10;
std::string hexstring = stringFormat("%X", hex);
Spójrz na więc odpowiedź z iFreilicht i wymagany plik nagłówka szablonu stąd GIST !
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-06 16:18:52
Odpowiedź Kornela Kisielewicza jest świetna. Ale niewielki dodatek pomaga wychwycić przypadki, w których wywołujesz tę funkcję z argumentami szablonu, które nie mają sensu (np. float) lub które spowodowałyby bałagan w kompilatorze (np. typ zdefiniowany przez użytkownika).
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();
}
Edytowałem to, aby dodać wywołanie std::to_string, ponieważ 8-bitowe typy liczb całkowitych (np. std::uint8_t
przekazane wartości) do std::stringstream
są traktowane jako znak, co nie daje pożądanego wyniku. Przekazywanie takich liczb całkowitych do std::to_string
obsługuje je poprawnie i nie rani rzeczy przy użyciu innych, większych typów całkowitych. Oczywiście w takich przypadkach może wystąpić niewielki spadek wydajności, ponieważ wywołanie std:: to_string jest niepotrzebne.
Uwaga: dodałbym to w komentarzu do oryginalnej odpowiedzi, ale nie mam rep do komentowania.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-25 18:47:34
Spróbuj tego:
#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
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-10 14:43:17