æ3ç§æ¹å¼å®ç°ï¼å
¶ä¸ä¸¤ç§æ¯ä½¿ç¨ç³»ç»å½æ°ï¼å¦ä¸ç§æ¯ç´æ¥èªå·±ç¼åã
使ç¨ç³»ç»å½æ°å®ç°è¦å å
¥#include <stdlib.h>ï¼èªå·±ç¼ååä¸éè¦è¿ä¸ªå¤´æ件ã
ä¸é¢ç代ç å°±æ¯3ç§æ¹å¼çå®ç°ï¼å
æ¬2ä½çæ´æ°åä»»ææ´æ°ï¼2ç31次æ¹ä»¥å
ï¼é½å¯ä»¥ãå¯èªå·±éæ©éè¦çå®ç°æ¹å¼ã
å©ç¨ç³»ç»å½æ°æ
1. char * itoa ( int value, char * str, int base );valueæ¯è¦è½¬åçæ°åï¼stræ¯è½¬ååçå符串åå¨çä½ç½®ï¼baseæ¯è¿å¶æ°ï¼ä½æ¯è¿ä¸ªå½æ°ä¸æ¯æ åCå½æ°ï¼æäºç¼è¯å¨æ¯ä¸æ¯æçï¼ï¼ãæ以代ç å¯ä»¥ä¸ºï¼
1
2
3
4
5
6
7
char buffer [33]; //ç¨äºåæ¾è½¬æ¢å¥½çåå
è¿å¶å符串ï¼å¯æ ¹æ®éè¦å®ä¹é¿åº¦
char * inttohex(int aa)
{
itoa (aa, buffer, 16);
return (buffer);
}
2. sprintf(str,"%x",value);stræ¯è½¬ååå¨çä½ç½®ï¼%x表示åå
è¿å¶æ ¼å¼ï¼valueæ¯è¦è½¬åçæ°åãæ以代ç å¯ä»¥ä¸ºï¼
1
2
3
4
5
6
7
char buffer [33]; //ç¨äºåæ¾è½¬æ¢å¥½çåå
è¿å¶å符串ï¼å¯æ ¹æ®éè¦å®ä¹é¿åº¦
char * inttohex(int aa)
{
sprintf(buffer, "%x", aa);
return (buffer);
}
3. èªå·±ç¼å
å¦æåæ°åªè¦ä¸¤ä½æ°çæ´æ°ï¼é£ä¹å¾ç®åã代ç å¦ä¸ï¼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
char buffer [3]; //ç¨äºåæ¾è½¬æ¢å¥½çåå
è¿å¶å符串ãç±äºåªè¦æ¯æ2ä½æ´æ°ï¼æ以é¿åº¦3å³å¯
char * inttohex(int aa)
{
if (aa / 16 < 10) //计ç®åä½ï¼å¹¶è½¬æ¢æå符
buffer[0] = aa / 16 + '0';
else
buffer[0] = aa / 16 - 10 + 'A';
if (aa % 16 < 10) //计ç®ä¸ªä½ï¼å¹¶è½¬æ¢æå符
buffer[1] = aa % 16 + '0';
else
buffer[1] = aa % 16 - 10 + 'A';
buffer[2] = '\0'; //å符串ç»ææ å¿
return (buffer);
}
å¦æåæ°æ¯ä»»ææ´æ°ï¼ç±äºè®¡ç®æ¹æ³æ¯æ¯æ¬¡é½é¤ä»¥16å对16åä½æ°ï¼ä½æ°ä»¥ååºç顺åºæåå°±æ¯ç»æï¼æ以æä½³æ¹æ³æ¯ç¨éå½å½æ°ï¼å½ç¶å¾ªç¯ä¹å¯ä»¥ï¼ä½éè¦æååè¿è¡ååºï¼ãéå½ä»£ç å¦ä¸ï¼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
char buffer [33]; //ç¨äºåæ¾è½¬æ¢å¥½çåå
è¿å¶å符串ï¼å¯æ ¹æ®éè¦å®ä¹é¿åº¦
char * inttohex(int aa)
{
static int i = 0;
if (aa < 16) //éå½ç»ææ¡ä»¶
{
if (aa < 10) //å½åæ°è½¬æ¢æå符æ¾å
¥å符串
buffer[i] = aa + '0';
else
buffer[i] = aa - 10 + 'A';
buffer[i+1] = '\0'; //å符串ç»ææ å¿
}
else
{
inttohex(aa / 16); //éå½è°ç¨
i++; //å符串索å¼+1
aa %= 16; //计ç®å½åå¼
if (aa < 10) //å½åæ°è½¬æ¢æå符æ¾å
¥å符串
buffer[i] = aa + '0';
else
buffer[i] = aa - 10 + 'A';
}
return (buffer);
}
æåæµè¯ä»£ç å¦ä¸ï¼ä»¥sprintf为ä¾ï¼å
¶ä½åªè¦æ¿æ¢inttohexå½æ°ä¸ç代ç å
容å³å¯ï¼ï¼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdio.h>
#include <stdlib.h>
char buffer [33]; //ç¨äºåæ¾è½¬æ¢å¥½çåå
è¿å¶å符串ï¼å¯æ ¹æ®éè¦å®ä¹é¿åº¦
char * inttohex(int aa)
{
sprintf(buffer, "%x", aa);
return (buffer);
}
int main ()
{
int num;
char * hex_str;
printf ("Enter a number: ");
scanf ("%d",&num);
hex_str = inttohex (num);
printf ("Hexadecimal number: %sH\n", hex_str);
return 0;
追é®ææ¯ç¨åçæºè¾åºç»è§¦æ¸å±ç»å¾ç¨çï¼ä½¿ç¨æ¶å¿
须以0x..æ ¼å¼ä½¿ç¨ï¼ç´æ¥è¾åº64ï¼ä¸è¡ï¼å¿
é¡»æ¯0x64æè¡ï¼