C++ 字符串 0CF00400 如何转换成16进制 0X0CF00400

最好能写个函数直接用

第1个回答  2015-04-17


int main(){
int t=0;
int i=0;
char ch;
char * str="0CF00400";
while((ch=str[i])!='\0'){
if(ch>0x39)
t=t*16+(ch-0x37);
else
t=t*16+(ch-0x30);
i++;
}
printf("Hex:%x,Dec:%d",t,t);
return 0;
}

 好懒,代码基本都给你了,稍微改一下就好了啊

int strToInt(char* str){
int t=0;
int i=0;
char ch;
//char * str="0CF00400";
while((ch=str[i])!='\0'){
//printf("%c\t%d\n",ch,ch>0x39?(ch-0x37):(ch-0x30));
if(ch>0x39)
t=t*16+(ch-0x37);
else
t=t*16+(ch-0x30);
i++;
}
return t;
}

int main(){
int t=0;
t=strToInt("0CF00400");
printf("Hex:%x,Dec:%d",t,t);
return 0;
}

本回答被提问者和网友采纳
第2个回答  2015-04-17
//#include "stdafx.h"//vc++6.0加上这一行.
#include <iostream>
#include "iomanip"
using namespace std;
int main(void){
    char *s="0CF00400";
    cout.setf(ios::uppercase);
    cout << "0x" << setfill('0') << hex << setw(8) << strtol(s,NULL,16) << endl;
    return 0;
}

第3个回答  2015-04-17
写一个函数字符串转数字

转成2进制,就可以随便转其余格式了。
可以用_itoa()
第4个回答  2015-04-17
用format函数格式化一下
相似回答