整数转16进制字符串,不用系统函数

来源:互联网 发布:linux中cat命令详解 编辑:程序博客网 时间:2024/04/28 17:22

伪代码:

 ConvertInt2Hex: dim n,hexStr loop:      if n == 0        break;    dim tmp = n % 16    if tmp >= 0 && tmp <= 9       hexStr <- hexStr.append('0' + tmp)    else         hexStr <- hexStr.append('a'+tmp-10)    n <- n / 16 end loop reverse(hexStr) end ConvertInt2Hex

c++

#include <stdio.h>#include <string.h>int main(){int input=0;int temp=0;int i=0;int j=0;char result[100];printf("input a number:\n");scanf("%d",&input);while(input!=0){temp=input%16;if(temp>=0 && temp<10){result[i]=temp+'0';i++;}else{result[i]=temp+'A'-10;     i++;}input=input/16;}result[i]='\0';for (j=strlen(result)-1;j>=0;j--){printf("%c",result[j]);}printf("\n");return 0;}


# include <iostream># include <sstream>using namespace std;int main(){    const char map[] = "0123456789ABCDEF";    unsigned int i = 0xABCDEF12;    stringstream buffer;    while (i)    {        buffer << map[i % 16];        i /= 16;    }    buffer << ends;    string tmp = buffer.str();    string s(tmp.rbegin(), tmp.rend());    cout << s << endl;    return 0;}



0 0