JonsenElizee

Software Developing Blog

"An idea is fragile . It can be killed by a scornful smile or a yawn .It can be mound down by irony and scared to death by a cold look."
"Most cultures throughout human history have not liked creative individuals .They ignore them or kill them.It is a very efficient way of stopping creativity."

------Advertising boss Charles Browe and Howard Gardner ,professor at Harvard

   :: 首页 :: 新随笔 ::  ::  :: 管理 ::
Here is simple implementation for converting int value to 0x string with out sprintf and so on.
Any better way is expected ......
 1 #include <assert.h>
 2 /*
 3  * convert int value to 0x string.
 4  *
 5  * int ipt input int value.
 6  * char* opt output string.
 7  */
 8 void int2Xstr(int ipt, char* opt)
 9 {
10     assert(ipt != NULL && opt != NULL);
11 
12     /* add prefix "0x" */
13     *opt++ = '0';
14     *opt++ = 'x';
15     opt +=7;
16 
17     /* number of 4bits-unit */
18     int num = sizeof(int)*2;
19     
20     /* using << and >> to get 4bits value and convert it to 0x char */
21     for(int i = 0; i < num; i ++)
22     {
23         /* negative value should be converted to unsigned one */
24         unsigned var = ipt < 0 ? (unsigned)(-ipt) : (unsigned)ipt;
25 
26         /* >> and << to clear other bits */
27         var >>= 4*i;
28         var <<= (num-1)*4;
29         var >>= (num-1)*4;
30 
31         /* convert to 0x char */
32         if(var >= 10) *opt-- = (var - 10+ 'A';
33         else *opt-- = var + '0';
34     }
35 }
36 int main()
37 {
38     char opt[32= {0};
39     int2Xstr(1234567890, opt);
40     puts(opt); /* 0x499602D2 */
41     getchar();
42     return 0;
43 }


posted on 2010-10-21 10:24 JonsenElizee 阅读(318) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


By JonsenElizee