C ++에서 16 진수 문자열에 대한 정수 변환하는 방법 합니까? 몇 가지 방법을

C ++ 에서 정수를 16 진수 문자열로 변환하는 방법 합니까?

몇 가지 방법을 찾을 수 있지만 대부분 C를 대상으로하는 것 같습니다. C ++에서이를 수행하는 기본 방법이없는 것 같습니다. 그래도 매우 간단한 문제입니다. 나는있어 int나중에 인쇄를위한 16 진수 문자열로 변환하고 싶은합니다.



답변

사용 <iomanip>std::hex. 인쇄하는 경우으로 보내십시오 std::cout. 그렇지 않은 경우 다음을 사용하십시오.std::stringstream

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

당신은 첫 번째를 앞에 추가 할 수 <<와 함께 << "0x"또는 당신이 원하는 경우에 당신이 무엇을 좋아.

관심있는 다른 조작은 std::oct(8 진수) 및 std::dec(10 진수로 돌아 가기)입니다.

발생할 수있는 한 가지 문제는이를 나타내는 데 필요한 정확한 양의 숫자를 생성한다는 사실입니다. setfillsetw이것을 사용 하여 문제를 피할 수 있습니다.

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

그래서 마지막으로 이러한 기능을 제안합니다.

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();
}

답변

더 가볍고 빠르게 만들기 위해 줄을 직접 채우는 것이 좋습니다.

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;
}

답변

사용 std::stringstream문자열과 특별한 조종로 변환 정수로베이스를 설정합니다. 예를 들면 다음과 같습니다.

std::stringstream sstream;
sstream << std::hex << my_integer;
std::string result = sstream.str();

답변

16 진수로 인쇄하면됩니다.

int i = /* ... */;
std::cout << std::hex << i;

답변

다음을 시도 할 수 있습니다. 작동 중입니다 …

#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;
}

답변

이 질문은 오래되었지만 아무도 언급하지 않은 이유가 놀랍습니다 boost::format.

cout << (boost::format("%x") % 1234).str();  // output is: 4d2

답변

int num = 30;
std::cout << std::hex << num << endl; // This should give you hexa- decimal of 30