unsigned int 转 16进制 的string,该如何解决

unsigned int 转 16进制 的string我想写个函数 想转换 数字 到字符串, 字符串是 16进制的 大家有没有什么

unsigned int 转 16进制 的string
我想写个函数 想转换 数字 到字符串, 字符串是 16进制的 大家有没有什么思路


例如:

输入 》58965 
输出 》"0x0655"

[解决办法]
可以使用scanf函数读入,简单写一段给你参考
int main()
{
int input;

scanf("%d",&input);
printf("0x%08x",input);

return 0;
}

你输入的10进制数字会被读入到input中,再以16进制打印出来
[解决办法]

C/C++ code
#include <iostream>#include <string>using namespace std;char ToHexChar(int n){    return n<10 ? n+'0' : n-10+'A';}string foo(unsigned int n){    char t, buff[32]={'0','x', 0};    int i = 2, j = 2;    do buff[i++] = ToHexChar(n%16); while (n/=16);    for (--i; j < i; ++j, --i)        t = buff[i], buff[i] = buff[j], buff[j] = t;    return buff;}int main(){    unsigned int n;    while (cin >> n) cout << foo(n) << endl;    return 0;}
[解决办法]
C/C++ code
// 58965的16进制是0xE655// 不一定是最佳方法#include <iostream>#include <string>using namespace std;string IntToHex(unsigned int num){    char *chp;    char ch, chl, chh;    string hex("0x");    chp = (char *)&num;    int int_size = sizeof(int);    for (int i=int_size; i>=0; i--)    {        ch = *(chp + i);        chh = (ch & 0xF0) >> 4;        chl = ch & 0x0F;        chh = chh>0x09 ? chh+0x37 : chh+0x30;        chl = chl>0x09 ? chl+0x37 : chl+0x30;        hex = hex + chh + chl;    }    return hex;}int main(){    unsigned int n;    cout << "int:";    cin >> n;    cout << "hex:" << IntToHex(n) << endl;    return 0;}
[解决办法]
C/C++ code
#include <iostream>using namespace std;char *DecToHex(char *hex, unsigned int dec) {     char ch, *left=hex, *right=hex;     do     {         if ((ch=dec%16)<10) *right++ = ch+'0';         else *right++ = ch+55;     }while ((dec>>=4) != 0);     *right-- = '\0';     while (left<right)     {         ch = *left;         *left++ = *right;         *right-- = ch;     }     return hex; } int main(){    int dec=58965;    char hex[30];    memset(hex,0,30);    DecToHex(hex,dec);    cout<<hex<<endl;    return 0;}
[解决办法]
引用楼主 chiwa737 的帖子:
我想写个函数 想转换 数字 到字符串, 字符串是 16进制的 大家有没有什么思路


例如:

输入 》58965
输出 》"0x0655"

[解决办法]
C/C++ code
#include <string>#include <iostream>#include <strstream>void unsigned_to_hex(unsigned int value, std::string& hex_string){   std::strstream buffer;   buffer.setf(std::ios::showbase);   buffer <<std::hex << value;      buffer >> hex_string;}int  main(){   unsigned int value;   std::cin >> value;   std::string hex_string;   unsigned_to_hex(value, hex_string);   std::cout << hex_string;   return 0;}