Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/131.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C+中的整数到十六进制字符串+;_C++_Decimal_Hex_Int - Fatal编程技术网

C++ C+中的整数到十六进制字符串+;

C++ C+中的整数到十六进制字符串+;,c++,decimal,hex,int,C++,Decimal,Hex,Int,如何在中将整数转换为十六进制字符串 我可以找到一些方法来做,但它们大多是针对C的。在C++中似乎没有一种天生的方法。这是一个相当简单的问题;我有一个int,我想把它转换成十六进制字符串,以便以后打印 使用。如果打印,只需将其发送到std::cout,如果不打印,则使用 最后,我建议这样一个函数: template< typename T > std::string int_to_hex( T i ) { std::stringstream stream; stream <

如何在中将整数转换为十六进制字符串

我可以找到一些方法来做,但它们大多是针对C的。在C++中似乎没有一种天生的方法。这是一个相当简单的问题;我有一个
int
,我想把它转换成十六进制字符串,以便以后打印

使用
。如果打印,只需将其发送到
std::cout
,如果不打印,则使用

最后,我建议这样一个函数:

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();
}
模板
std::字符串int_到_十六进制(ti)
{
std::stringstream;
流使用
。如果打印,只需将其发送到
std::cout
,如果不打印,则使用

最后,我建议这样一个函数:

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();
}
模板
std::字符串int_到_十六进制(ti)
{
std::stringstream;

流只需将其打印为十六进制数:

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

std::cout只需将其打印为十六进制数:

int i = /* ... */;
std::cout << std::hex << i;
inti=/*…*/;
std::cout
int num=30;
std::cout
int num=30;

std::cout使用
std::stringstream
将整数转换为字符串,并使用其特殊操纵器设置基数。例如:

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

sstream使用
std::stringstream
将整数转换为字符串,并使用其特殊操纵器设置基数。例如:

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

sstream您可以尝试以下方法。它正在工作

#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;
}
#包括
#包括
#包括
#包括
使用名称空间std;
模板
字符串到字符串(T,ios\u base和(*f)(ios\u base和)
{
ostringstream oss;

oss您可以尝试以下方法。它正在工作

#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;
}
#包括
#包括
#包括
#包括
使用名称空间std;
模板
字符串到字符串(T,ios\u base和(*f)(ios\u base和)
{
ostringstream oss;

oss对于那些发现许多/大部分ios::fmtflags
不适用于
std::stringstream
但喜欢Kornel在很久以前发布的模板想法的人,以下内容有效且相对干净:

#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);
#包括
#包括
模板
std::字符串hexify(ti)
{
std::stringbuf-buf;
标准::奥斯特雷姆操作系统(&buf);

os对于那些发现许多/大部分的
ios::fmtflags
不适用于
std::stringstream
但喜欢Kornel在很久以前发布的模板想法的人,下面的内容可以工作并且相对干净:

#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);
#包括
#包括
模板
std::字符串hexify(ti)
{
std::stringbuf-buf;
标准::奥斯特雷姆操作系统(&buf);

os为了使它更轻更快,我建议使用直接填充字符串

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

template std::string n2hextr(I w,size\t hex\u len=sizeof(I)为使其更轻更快,我建议使用直接填充字符串

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

template std::string n2hextr(I w,size\t hex\u len=sizeof(I)代码供您参考:

#include <iomanip>
#include <sstream>
...
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;
}
#包括
#包括
...
字符串intToHexString(int intValue){
字符串hextr;
///整数值转换为十六进制字符串
std::stringstream和ssstream;

sstream代码供您参考:

#include <iomanip>
#include <sstream>
...
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;
}
#包括
#包括
...
字符串intToHexString(int intValue){
字符串hextr;
///整数值转换为十六进制字符串
std::stringstream和ssstream;
sstream我有:

请查看来自iFreilicht的答案和此处所需的模板头文件!

我愿意:

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

看看iFreilicht的答案和这里所需的模板头文件!

看看我的解决方案,[1]是我从项目中逐字复制的,因此包含了一个德语API文档。我的目标是在我的实际需求中结合灵活性和安全性:[2]

  • 0x
    添加前缀
    呼叫方可以决定
  • 自动宽度扣除:减少键入
  • 显式宽度控件:为格式化而加宽,(无损)收缩以节省空间
  • 能够处理
    long
  • 限制为整数类型:避免无声转换带来意外
  • 易懂
  • 无硬编码限制

请看一下我的解决方案,[1]是我从项目中逐字复制的,因此包含了一个德语API文档。我的目标是在我的实际需求中结合灵活性和安全性:[2]

  • 0x
    添加前缀
    呼叫方可以决定
  • 自动宽度扣除:减少键入
  • 显式宽度控件:为格式化而加宽,(无损)收缩以节省空间
  • 能够处理
    long
  • 限制为整数类型:避免无声转换带来意外
  • 易懂
  • 无硬编码限制

感谢林肯在下面的评论,我已经改变了这个答案

下面的答案在编译时正确地处理8位整数。但是,它不需要C++17。如果没有C++17,则必须执行其他操作(例如,提供此函数的重载,一个用于uint8,一个用于int8,或者使用除“If constexpr”之外的内容,可能启用\u If)

模板
std::字符串int_到_十六进制(ti)
{
//确保使用有意义的模板参数调用此函数。注意:static_assert仅在C++11及更高版本中可用。
static_assert(std::is_integral::value,“模板参数'T'必须是基本整数类型(例如int、short等)”;
std::stringstream;

感谢Lincoln在下面的评论,我已经改变了这个答案

下面的答案在编译时正确地处理8位整数。但是,它不需要C++17。如果没有C++17,则必须执行其他操作(例如,提供此函数的重载,一个用于uint8\t,一个用于int8\t,或者使用除“If constexpr”之外的内容,可能启用
cout << (boost::format("%x") % 1234).str();  // output is: 4d2
int var = 20;
cout <<                          &var << endl;
cout <<                     (int)&var << endl;
cout << std::hex << "0x" << (int)&var << endl << std::dec; // output in hex, reset back to dec
#include  <iomanip>
#include <sstream>

template <class T, class T2 = typename std::enable_if<std::is_integral<T>::value>::type>
static std::string ToHex(const T & data, bool addPrefix = true);



template<class T, class>
inline std::string Convert::ToHex(const T & data, bool addPrefix)
{
    std::stringstream sstream;
    sstream << std::hex;
    std::string ret;
    if (typeid(T) == typeid(char) || typeid(T) == typeid(unsigned char) || sizeof(T)==1)
    {
        sstream << static_cast<int>(data);
        ret = sstream.str();
        if (ret.length() > 2)
        {
            ret = ret.substr(ret.length() - 2, 2);
        }
    }
    else
    {
        sstream << data;
        ret = sstream.str();
    }
    return (addPrefix ? u8"0x" : u8"") + ret;
}
#include <definition.h>
int main()
{
    std::cout << ToHex<unsigned char>(254) << std::endl;
    std::cout << ToHex<char>(-2) << std::endl;
    std::cout << ToHex<int>(-2) << std::endl;
    std::cout << ToHex<long long>(-2) << std::endl;

    std::cout<< std::endl;
    std::cout << ToHex<unsigned char>(254, false) << std::endl;
    std::cout << ToHex<char>(-2, false) << std::endl;
    std::cout << ToHex<int>(-2, false) << std::endl;
    std::cout << ToHex<long long>(-2, false) << std::endl;
    return 0;
}
public:template <class T,class U> U* Int2Hex(T lnumber, U* buffer)
{
    const char* ref = "0123456789ABCDEF";
    T hNibbles = (lnumber >> 4);

    unsigned char* b_lNibbles = (unsigned char*)&lnumber;
    unsigned char* b_hNibbles = (unsigned char*)&hNibbles;

    U* pointer = buffer + (sizeof(lnumber) << 1);

    *pointer = 0;
    do {
        *--pointer = ref[(*b_lNibbles++) & 0xF];
        *--pointer = ref[(*b_hNibbles++) & 0xF];
    } while (pointer > buffer);

    return buffer;
}
char buffer[100] = { 0 };
Int2Hex(305419896ULL, buffer);//returns "0000000012345678"
Int2Hex(305419896UL, buffer);//returns "12345678"
Int2Hex((short)65533, buffer);//returns "FFFD"
Int2Hex((char)18, buffer);//returns "12"

wchar_t buffer[100] = { 0 };
Int2Hex(305419896ULL, buffer);//returns L"0000000012345678"
Int2Hex(305419896UL, buffer);//returns L"12345678"
Int2Hex((short)65533, buffer);//returns L"FFFD"
Int2Hex((char)18, buffer);//returns L"12"
#include <iostream> 
#include <sstream>  

int main()
{
unsigned int i = 4967295; // random number
std::string str1, str2;
unsigned int u1, u2;

std::stringstream ss;
// INT to HEX
ss << (void*)i;       // <- FULL hex address using void pointer
ss >> str1;          //     giving address value of one given in decimals.
ss.clear();         // <- Clear bits
// HEX to INT
ss << std::hex << str1;   // <- Capitals doesn't matter so no need to do extra here
ss >> u1;
ss.clear();
// INT to HEX with 0x
ss << "0x" << (void*)i;   // <- Same as above but adding 0x to beginning
ss >> str2;
ss.clear();
// HEX to INT with 0x
ss << std::hex << str2;   // <- 0x is also understood so need to do extra here
ss >> u2;
ss.clear();
std::cout << str1 << std::endl; // 004BCB7F
std::cout << u1 << std::endl;   // 4967295
std::cout << std::endl;
std::cout << str2 << std::endl; // 0x004BCB7F
std::cout << u2 << std::endl;   // 4967295


return 0;
}
    static const char* digits = "0123456789ABCDEF";//dec 2 hex digits positional map
    char value_hex[3];//2 digits + terminator
    value_hex[0] = digits[(int_value >> 4) & 0x0F]; //move of 4 bit, that is an HEX digit, and take 4 lower. for higher digits use multiple of 4
    value_hex[1] = digits[int_value & 0x0F]; //no need to move the lower digit
    value_hex[2] = '\0'; //terminator