C Programming: Convert Hex Int to Char*

后端 未结 4 1670
借酒劲吻你
借酒劲吻你 2020-12-21 05:55

My question is how I would go about converting something like:

    int i = 0x11111111;

to a character pointer? I tried using the itoa() fun

4条回答
  •  别那么骄傲
    2020-12-21 06:56

    itoa is non-standard. Stay away.

    One possibility is to use sprintf and the proper format specifier for hexa i.e. x and do:

    char str[ BIG_ENOUGH + 1 ];
    sprintf(str,"%x",value);
    

    However, the problem with this computing the size of the value array. You have to do with some guesses and FAQ 12.21 is a good starting point.

    The number of characters required to represent a number in any base b can be approximated by the following formula:

    ⌈logb(n + 1)⌉

    Add a couple more to hold the 0x, if need be, and then your BIG_ENOUGH is ready.

提交回复
热议问题